Home

NI-VISA User Manual - scs.etti.tuiasi.ro

image

Contents

1. status viEnableEFvent instr VI_EVENT_IO_COMPLETION VI_QUEUE VI_NULL status viWriteAsync instr READ WAVFM CH1 14 amp jobID status viWaitOnEvent instr VI_EVENT_IO_COMPLETION 10000 amp etype amp event if status lt VI_SUCCESS status viTerminate instr VI_NULL jobID now the I O completion event should exist in the queue National Instruments Corporation 5 3 NI VISA User Manual Chapter 5 Message Based Communication status viWaitOnEvent instr VI_EVENT_IO_COMPLETION 0 amp etype amp event As long as an asynchronous operation is successfully posted if the return value from the asynchronous operation is greater than or equal to VI_SUCCESS there will always be exactly one I O completion event resulting from the transfer However if the asynchronous operation viReadAsync or viWriteAsync returns an error code there will not be an I O completion event In the above example if the I O has not completed in 10 seconds the call to viTerminate aborts the I O and results in the I O completion event being generated The I O completion event has attributes containing information about the transfer status return count and more For a more complete description of the I O completion event and its attributes refer to the NJ VISA Programmer Reference Manual or to the NI VISA online help For a more detaile
2. Refer to the NI VISA online help or the NI VISA Programmer Reference Manual for a complete list and description of the available attributes Asynchronous Read Write Services In addition to the synchronous read and write services VISA has operations for asynchronous I O The functionality of these operations is identical to that of the synchronous ones therefore the topics covered in the previous section apply to asynchronous read and write operations as well The main difference is that a job ID is returned from the asynchronous T O operations instead of the transfer status and return count You then wait for an I O completion event from which you can get that information Note You must enable the session for the I O completion event before beginning an asynchronous transfer One other difference is the timeout attribute VI_ATTR_IMO_VALUE This attribute may or may not apply to asynchronous operations depending on the implementation If you want to ensure that asynchronous operations never time out even on implementations that do use the timeout attribute set the attribute value to VI_TMO_INFINITE If you want to ensure that asynchronous operations do not last beyond a certain period of time even on implementations that do not use the timeout attribute you should abort the I O using the viTerminate operation if it does not complete within the expected time as shown in the following code
3. return 1 Open communication with VXI Device at Logical Address 16 NOTE For simplicity we will not show error checking a status viOpen defaultRM VXI0 16 INSTR VI_NULL VI_NULL amp instr Enable the driver to detect the interrupts status viEnableEvent instr VI_EVENT_VXI_SIGP VI_QUEUE VI_NULL Send the commands to the oscilloscope to capture the waveform and interrupt when done status viWaitOnEvent instr VI_EVENT_VXI_SIGP 5000 amp eventType amp eventData if status lt VI_SUCCESS No interrupts received after 5000 ms timeout viClose defaultRM return 1 Obtain the information about the event and then destroy the event In this case we want the status ID from the interrupt status viGetAttribute eventData VI_ATTR_SIGP_STATUS_ID amp statID status viClose eventData Your code should read data from the instrument and process it NI VISA User Manual 2 8 National Instruments Corporation Chapter 2 Introductory Programming Examples Stop listening to events status viDisableEvent instr VI_EVENT_VXI_SIGP VI_QUEUE Close down the system status viClose instr status viClose defaultRM return 0 Example 2 3 Discussion As you can see this programming code presents some new functions you need to use The first two functions you will notice are viEnableEvent and viDisableEvent
4. Note Not all VISA implementations may support setting the size of either the serial input or output buffers In such an implementation the viSetBuf operation will return a warning While this should not affect most programs you can at least detect this lack of support if a specific buffer size is required for performance reasons If serial buffer control is not supported in a given implementation we recommend that you use some form of handshaking controlled via the VI_ATTR_ASRL_FLOW_CNTRL attribute if possible to avoid loss of data When using formatted I O in conjunction with serial devices calling viFlush ona formatted I O buffer has the same effect on the corresponding serial buffer For example invoking viFlush with VI_WRITE_BUF flushes the formatted I O output buffer first and then the low level serial output buffer Similarly vI_WRITE_BUF_DISCARD empties the contents of both the formatted I O and low level serial output buffers National Instruments Corporation 5 11 NI VISA User Manual Chapter 5 Message Based Communication Example VISA Message Based Application The following is an example VISA application using message based communication C Note This example shows C source code You can find the same example in Visual Basic syntax in Appendix A Visual Basic Examples Example 5 1 include visa h int main void ViSession defaultRM instr ViUInt32 retCount ViChar idnRe
5. Error initializing VISA return status exiting Find the first matching VXI instrument sprintf regExToUse a af ae Be ae 2 VXI 0 9 INSTR VI_ATTR_MANF_ID 0x x amp amp VI_ATTR_MODEL_CODE 0x x MANF_ID MODEL_CODE status viFindRsrc defaultRM if status lt VI_SUCCESS Error finding resources regExToUse VI_NULL VI_NULL viClose defaultRM return status status viOpen defaultRM desc if status lt VI_SUCCESS viClose defaultRM return status instrSesn instr Do not close defaultRM return VI_SUCCESS 4 10 xiting VI_NULL VI_NULL amp instr as that would close instr too desc X A National Instruments Corporation Chapter 4 Initializing Your VISA Application Configuring a Session After the Resource Manager opens a session communication with the device can usually begin using the default session settings However in some cases such as ASRL serial resources you need to set some other parameters such as baud rate parity and flow control before proper communication can begin GPIB and VXI sessions may have still other configuration parameters to set such as timeouts and end of transmission modes although in general the default settings should suffice Accessing Attributes VISA uses two operations for obtaining and setting parameters viGetAttribute and viSetAttribute
6. Rem Error initializing VISA exiting Exit Sub End If Rem Open communication with Serial Port 1 Rem Set the timeout for message based communication stat viSetAttribute sesn VI_ATTR_TMO_VALUE 5000 Rem Lock the serial port so that stat viLock sesn VI_EXCLUSIVE_LOCK 5000 Rem Set serial port settings as needed Rem Your code should process the data Rem Close down the system stat viClose sesn stat viClose df1tRM End Sub National Instruments Corporation A 5 nothing else can use it stat viSetAttribute sesn VI_ATTR_ASRL_ BAUD 2400 stat viSetAttribute sesn VI_ATTR_ASRL_DATA_BITS 7 Rem Ask the device for identification stat viWrite sesn IDN 5 retCount stat viRead sesn buffer MAX_CNT retCount Rem Unlock the serial port before ending the program stat viUnlock sesn Visual Basic Examples Rem NOTE For simplicity we will not show error checking stat viOpen dfl1tRM ASRL1 INSTR VI_NULL VI_NULL sesn Rem Defaults 9600 Baud no parity 8 data bits 1 stop bit NI VISA User Manual Appendix A Visual Basic Examples Example 4 1 Private Sub vbMain Dim stat As ViStatus Dim df1ltRM As ViSession Dim sesn As ViSession Rem Open Default R stat viOpenDefaultRM df1tRM If stat lt VI_SUCCESS Then Rem Error initializing VISA exiting Exit Sub End If Rem Access other resources stat
7. viGetAttribute self VI_ATTR_MEM_SPACE mSpace viMapAddress self mSpace offs amp H100 VI_FALSE VI_NULL addr ek16 self addr Value Access a different register by manipulating the pointer ek16 self addr 2 Value viUnmapAddress self viMemFr self offs Close down the system viClose self viClose df1tRM Appendix A Visual Basic Examples Example 7 1 Visual Basic does not support callback handlers so currently the only way to handle events is through viWaitOnEvent Because Visual Basic does not support asynchronous operations either this example uses the viRead call instead of the viReadAsync call Private Sub vbMain Const MAX_CNT 1024 Dim stat As ViStatus Dim df1tRM As ViSession Dim sesn As ViSession Dim bufferHandle As String Dim retCount As Long Dim etype As ViEventType Dim event As ViEvent Dim stb As Integer Rem Begin by initializing the system Rem NOTE For simplicity we will not show error checking stat viOpenDefaultRM df1tRM If stat lt VI_SUCCESS Then Rem Error initializing VISA exiting Exit Sub End If Rem Open communication with GPIB device at primary address 2 stat viOpen df1ltRM GPIBO 2 INSTR VI_NULL VI_NULL sesn Rem Allocate memory for buffer Rem In addition allocate space for the ASCII NULL character bufferHandler Space MAX_CNT 1 Rem Enable the driver to detect events stat viEnableEvent sesn
8. by invoking viClose on the list reference fList National Instruments Corporation 4 5 NI VISA User Manual Chapter 4 Initializing Your VISA Application Finding VISA Resources Using Regular Expressions Using viFindRsrc to locate a resource in a VISA system requires a way for you to identify which resources you are interested in The VISA Resource Manager accomplishes this through the use of regular expressions which specify a match for certain resources in the system Regular expressions are strings consisting of ordinary characters as well as certain characters with special meanings that you can use to search for patterns instead of specific text Regular expressions are based on the idea of matching where a given string is tested to see if it matches the regular expression that is to determine if it fits the pattern of the regular expression You can apply this same concept to a list of strings to return a subset of the list that matches the expression The following table defines the special characters and syntax rules used in VISA regular expressions Special Characters and Operators Meaning Matches any one character Makes the character that follows it an ordinary character instead of special character For example when a question mark follows a backslash 2 it matches the character instead of any one character list Matches any one character from the enclosed 1ist You can use a hyph
9. register offset in device address space If you need more than a single map for a device you must open a second session to the device because VISA currently supports only a single map per session There is very low overhead in having two sessions because sessions themselves do not take much memory However you need to keep track of two session handles Notice that this is different from the maximum number of windows you can have on a system The hardware for the controller you are using may have a limit on the number of unique windows it can support When you are finished with the window or need to change the mapping to another address or address space you must first unmap the window using the viUnmapAddress operation All you need to specify is which session you used to perform the map status viUnmapAddress instr National Instruments Corporation 6 7 NI VISA User Manual Chapter 6 Register Based Communication Operations versus Pointer Dereference After the viMapAddress operation returns the pointer you can use it to read or write registers VISA provides the viPeekxXx and viPokeXX operations to perform the accesses On many systems the viMapAddress operation returns a pointer that you can also dereference directly rather than calling the LLA operations The performance gain achievable by using pointer dereferences over operation invocations is extremely system dependent To determine whether you can use
10. viFindRsrc defaultRM VXI 0 9 INSTR amp fList NI VISA User Manual numInstrs desc 4 4 National Instruments Corporation if Chapter 4 Initializing Your VISA Application status lt VI_SUCCESS Error finding resources exiting viClose defaultRM return status Open a session to each and determine if it matches while numInstrs status viOpen defaultRM desc VI_NULL VI_NULL amp instr if status lt VI_SUCCESS viFindNext fList desc continue status viGetAttribute instr VI_ATTR_MANF_ID amp iManf if status lt VI_SUCCESS iManf MANF_ID viClose instr viFindNext fList desc continue status viGetAttribute instr VI_ATTR_MODEL_CODE amp iModel j if status lt VI_SUCCESS iModel MODEL_CODE viClose instr viFindNext fList desc continue We have a match return the session without closing it instrSesn instr viClose fList Do not close defaultRM as that would close instr too return VI_SUCCESS No match was found return an error viClose fList viClose defaultRM return VI_ERROR_RSRC_NFOUND As this example shows you can use viFindRsrc to get a list of y ay ay 7 matching resource names which you can then further examine one at a time using viFindNext Remember to free the space allocated by the system
11. viOpen df1ltRM GPIB 1 INSTR VI_NULL VI_NULL sesn Rem Use device and eventually close it stat viClose sesn stat viClose df1tRM End Sub NI VISA User Manual A 6 National Instruments Corporation Appendix A Visual Basic Examples Example 4 2 Rem Find the first matching device and return a session to it Private Function AutoConnect instrSesn As ViSession As ViStatus Const MANF_ID G amp HFF6 12 bit VXI manufacturer ID of a device Const MODEL _CODE amp HOFE 12 bit or 16 bit model code of a device Dim stat As ViStatus Dim df1tRi As ViSession Dim sesn As ViSession Dim fList As ViFindList Dim desc As String VI_FIND_BUFLEN Dim nList As Long Dim iManf As Integer Dim iModel As Integer stat viOpenDefaultRM df1tRM If stat lt VI_SUCCESS Then Rem Error initializing VISA exiting AutoConnect stat Exit Function End If Rem Find all VXI instruments in the system stat viFindRsrc df1ltRM VXI 0 9 INSTR fList nList desc If stat lt VI_SUCCESS Then Rem Error finding resources exiting viClose df1tRM AutoConnect stat Exit Function End If National Instruments Corporation A 7 NI VISA User Manual Appendix A Visual Basic Examples Rem Open a session to each and determine if it matches While nList stat viOpen df1ltRM desc VI_NULL VI_NULL sesn If stat gt VI_SUCCESS Then stat viGetAttribute se
12. 4 10 bulletin board support B 1 National Instruments Corporation C callbacks 7 5 to 7 8 callback modes 7 6 to 7 7 definition 7 1 direct 7 6 event context 7 11 independent queues 7 7 interrupt callback handlers 9 3 to 9 4 programming considerations 2 7 sample code 7 8 to 7 10 suspended 7 6 userHandle parameter 7 7 to 7 8 clear services 4 4 to 4 5 communication channels See also message based communication register based communication closing 3 6 opening 3 5 to 3 6 programming considerations 3 5 to 3 6 customer communication xiii B 1 to B 2 D device triggering 4 5 documentation conventions used in manual x how to use documentation set xi organization of manual ix x related documentation xi xii E electronic support services B 1 to B 2 e mail support B 2 event handling programming examples example 7 1 7 9 to 7 11 NI VISA User Manual Index Visual Basic examples A 4 A 12 to A 13 events callbacks 7 5 to 7 8 callback modes 7 6 to 7 7 definition 7 1 event context 7 11 independent queues 7 7 interrupt callback handlers 9 3 to 9 4 programming considerations 2 7 sample code 7 8 to 7 10 userHandle parameter 7 7 to 7 8 definition 7 1 enabling and disabling 7 3 to 7 4 T O completion event 4 3 to 4 4 life of event context 7 11 queuing 7 4 to 7 5 definition 7 1 event context 7 11 programming considerations 2 7 sample code 7 8 to 7 10 supported events 7 2 to
13. Due to their asynchronous nature callbacks can be difficult to incorporate into a traditional sequential flow program Therefore we recommend the queuing method of handling events for new users If you are an experienced user or understand callback concepts look at the Callbacks section in Chapter 7 VISA Events Queuing When using a software queue the driver detects the asynchronous event but does not alert the program to the occurrence Instead the driver maintains a list of events that have occurred so that the program can retrieve the information later With this technique the program can periodically poll the driver for event information or halt the program until the event has occurred Example 2 3 programs an oscilloscope to capture a waveform When the waveform is complete the instrument generates a VXI interrupt so the program must wait for the interrupt before trying to read the data National Instruments Corporation 2 7 NI VISA User Manual Chapter 2 Introductory Programming Examples Example 2 3 include visa h int main void ViStatus status For checking errors K ViSession defaultRM instr Communication channels if ViEventType eventType To identify event ViEvent eventData To hold event info ViUInt16 statID Interrupt Status ID Begin by initializing the system ve status viOpenDefaultRM amp defaultRM if status lt VI_SUCCESS Error Initializing VISA exiting
14. In VISA userHandle gives the application more modularity than is possible with global variables In this case the application can allocate a data structure to hold information locally When it installs the callback handler it can pass the reference to this data structure to the callback handler via the userHandle This means that the handler can store the information in the local data structure rather than a global data structure For another example consider an application that installs a handler with a fixed value of 0x1 for the userHandle parameter It can install the same handler with a different value say 0x2 for the same event type on another session However installations of the same handler are different from one another Both handlers are invoked when the event of the given type occurs but in one invocation the value passed to userHandle is 0x1 and in the other it is 0x2 As a result you can uniquely identify VISA event handlers by a combination of the handler address and user context pair This structure also is important when the application attempts to remove the handler The operation viUninstallHandler requires not only the handler s address but also the userHandle value to correctly identify which handler to remove Queuing and Callback Mechanism Sample Code NI VISA User Manual Example 7 1 demonstrates the use of both the queuing and callback mechanisms in event handling In the program a message is sent to a G
15. given earlier in this manual The examples use the same numbering sequence for easy reference These examples use the VISA data types where applicable This feature is available only on Windows 95 NT To use this feature select the VISA library visa32 d11 as a reference from Visual Basic This makes use of the type library embedded into the DLL Windows 3 x users Use the native Visual Basic types as described in the NI VISA online help or NI VISA Programmer Reference Manual in the Data Types section National Instruments Corporation A 1 NI VISA User Manual Appendix A Visual Basic Examples Example 2 1 Private Sub vbMain Const MAX_CNT 200 viStatus ViSession stat df1tRM sesn As As As As As Dim Dim Dim viSession retCount buffer Dim Long Dim String MAX_CNT Rem Begin by initializing the system stat viOpenDefaultRM df1tRM If stat lt VI_SUCCESS Then Rem Exit Sub End If Rem Open communication with GPIB Devi Rem NOTE we will not For simplicity Error initializing VISA exiting ce at Primary Addr 1 show error checking stat viOpen df1ltRM GPIBO 1 INSTR VI_NULL VI_NULL sesn Rem Set the timeout for message based communication stat viSetAttribute sesn VI_ATTR_TMO_VALUE 5000 Rem Ask the device for identification stat viWrite sesn IDN 5 retCount stat viRead sesn buffer MAX_CNT retCount Rem Your code should process
16. viClose instr status viClose defaultRM return 0 National Instruments Corporation 6 9 NI VISA User Manual Chapter 6 Register Based Communication Bus Errors The LLA operations do not report bus errors In fact viPeekxx and viPokexXx do not report any error conditions However the HLA operations do report bus errors When using the LLA operations you must ensure that the addresses you are accessing are valid Comparison of High Level and Low Level Access Speed t Note Ease of Use NI VISA User Manual In terms of the speed of developing your application the HLA operations are much faster to implement and debug because of the simpler interface and the status information received after each access For example HLA operations encapsulate the mapping and unmapping of hardware windows which means that you do not need to call viMapAddress and viUnmapAddress separately For speed of execution the LLA operations perform faster when used for several random register I O accesses in a single window If you know that the next several accesses are within a single window you can perform the mapping just once and then each of the accesses has minimal overhead The HLA operations will be slower because they must perform a map access and unmap within each call Even if the window is correctly mapped for the access the HLA call at the very least needs to perform some sort of check to determine if it needs to
17. viOpen df1tRM communication with VXI Device at Logical Address 16 we will not show error checking VXI0O 16 INSTR VI_NULL VI_NULL sesn VI_A16_SPACE mSpace stat 0 viMapAddress sesn mSpace amp H40 VI_FALSE VI_NULL addr addr Rem Access a different register by manipulating the pointer addr t 23 viPeek16 sesn Value viPeek16 sesn Value stat viUnmapAddress sesn Rem Close down the system stat stat viClose sesn viClose df 1tRM End Sub NI VISA User Manual A 10 National Instruments Corporation Appendix A Visual Basic Examples Example 6 2 Private Dim Dim Dim Dim Dim Dim Dim Rem stat TE AG Stat Stat Rem Sub vbMain stat As ViStatus df1ltRM As ViSession self As ViSession addr As ViAddr offs As Long mSpace As Integer Value As Integer Begin by initializing the system viOpenDefaultRM df1tRM stat lt VI_SUCCESS Then Rem Error initializing VISA exiting Exit Sub If Open communication with VXI Device at Logical Address 0 NOTE For simplicity we will not show error checking viOpen df1ltRM VXI0O 0 INSTR VI_NULL VI_NULL self Allocate a portion of the device s memory viMemAlloc self amp H100 offs Stat stat viPe Rem viPe stat stat Rem stat stat End Sub National Instruments Corporation A 11 NI VISA User Manual Determine where the shared memory resides
18. 4 programming with VISA See also programming considerations for NI VISA communication channels 3 5 to 3 6 interface independence example 3 8 to 3 9 register communication 3 7 to 3 8 Resource Manager 3 6 to 3 7 terminology 3 3 to 3 5 Q queuing 7 4 to 7 5 definition 7 1 event context 7 11 programming considerations 2 7 sample code 7 8 to 7 10 R read write services asynchronous 4 3 to 4 4 synchronous 4 2 to 4 3 register based communication 5 1 to 5 13 comparison of high and low level access 5 10 to 5 11 accessing multiple address spaces 5 11 National Instruments Corporation l 5 Index ease of use 5 10 speed 5 10 examples example 2 2 2 5 to 2 7 example 5 1 5 9 to 5 10 Visual Basic examples A 3 A 7 High Level Access operations overview 3 7 to 3 8 purpose and use 5 2 to 5 3 high level block operations 5 4 to 5 5 Low Level Access operations 5 5 to 5 10 bus errors 5 10 computer access overview 5 5 to 5 7 example 5 9 to 5 10 operations versus pointer deference 5 8 overview 3 8 pointer manipulation 5 8 to 5 9 using VISA for performing 5 7 to 5 8 overview 5 1 to 5 2 shared memory operations 5 11 to 5 13 overview 5 11 to 5 12 sample code 5 12 to 5 13 when to use note 5 11 Register based devices RBDs 5 1 resizing formatted I O buffers 4 10 resource definition 3 3 to 3 4 Resource Manager See VISA Resource Manager S serial I O buffers controlling 4 11 serial p
19. 4 Initializing Your VISA Application R_TERMCHAR_ EN sets whether a termination character VI_ATTR_TERMCHAR will be used on read operations VIA specified by e VI_ATTR_S END_END_EN determines whether to use an END bit on your write operations Defaults to vI_TRUE Various interfaces have other types of attributes that may affect channel communication The following two VXI attributes are important for high level accesses s VI_A R_D EST_BYTE_ORDER specifies whether to write words in big endian VILA R_S or little endian byte order Defaults to VI_BIG_ENDIAN RC_BYTE_ORDER Specifies whether to read words in big endian or little endian byte order Defaults to VI_BIG_ENDIAN Because ASRL devices have much more variation in the communication channel be sure to set the following parameters correctly e VI_ATTR_ASRL_BAUD sets the baud rate Defaults to 9600 e VI_ATTR_ASRL_DATA_BITS sets the number of data bits Defaults to 8 e VI_ATTR_ASRL_PARITY sets the parity Defaults to VI_ASRL_PAR_NONE e VI_ATTR_ASRL_STOP_BITS sets the number of stop bits Defaults to VI_ASRL_STOP_ONE 10 e VI_ATTR_ASRL_FLOW_CNTRL sets the method for limiting overflow on transfers between the devices Defaults to VI_ASRL_FLOW_NONE no method of flow control Check the Serial Port Support section i
20. 418 1111 E Mail Support Currently USA Only You can submit technical support questions to the applications engineering team through e mail at the Internet address listed below Remember to include your name address and phone number so we can contact you with solutions and suggestions support natinst com Telephone and Fax Support National Instruments has branch offices all over the world Use the list below to find the technical support number for your country If there is no National Instruments office in your country contact the source from which you purchased your software to obtain support Country Australia Austria Belgium Brazil Canada Ontario Canada Qu bec Denmark Finland France Germany Hong Kong Israel Italy Japan Korea Mexico Netherlands Norway Singapore Spain Sweden Switzerland Taiwan United Kingdom United States NI VISA User Manual Telephone 03 9879 5166 0662 45 79 90 0 02 757 00 20 011 288 3336 905 785 0085 514 694 8521 45 76 26 00 09 725 725 11 01 48 14 24 24 089 741 31 30 2645 3186 03 6120092 02 413091 03 5472 2970 02 596 7456 5 520 2635 0348 433466 32 84 84 00 2265886 91 640 0085 08 730 49 70 056 200 51 51 02 377 1200 01635 523545 512 795 8248 B 2 Fax 03 9879 6277 0662 45 79 90 19 02 757 03 11 O11 288 8528 905 785 0086 514 694 4399 45 76 26 02 09 725 725 55 01 48 14 24 14 089 714 60 35 2686 8505 03 6120095 02 41309215 03 5472 2977 02 5
21. ARR ARS 3 2 Interactive Control of VISA r cectiessecesteiussveveus spacey setvesuesesabevsdesusdecduie Maceratueedeensenes 3 3 Programming With VISA wo eee E E EEEE S ERE ERE 3 7 Beginning Terminology siis e aa awe aan vad R ER 3 7 National Instruments Corporation v NI VISA User Manual Contents Communication Channels 0 0 ccccesesceseeseceeceseeseeeeeseeseseseaecseeesecsaesaecneenaes 3 8 The Resource Manager irice siri esios teats sise sae irois oea tiesp rae tisie 3 10 Register Communication sssseeeseeeesseresreresrssstrrsreersresrsreeterrnrerssreresreeesreee 3 11 Example of Interface Independence nsseeeseeeesseeereseesersserrrsrerrsreerrsreresrsse 3 12 Chapter 4 Initializing Your VISA Application Tint th oMi oeme inn ach cence E EE RE EO r E E Wage ea A eee sis 4 1 Opening Sesson i menpa ae a e e iain hae aes 4 1 EX ripe Ae oee e a AN E Na AEE E aa 4 2 Finding RESOULCES oina EEE EAE E T RS 4 4 Example A223 e nni i E A E E A N RRR 4 4 Finding VISA Resources Using Regular Expressions s eeseeeeerrererrerreseee 4 6 Attribute Based Resource Matching 00 eee eeeeecseeesecseceseceeeeseeeeeseeeeees 4 8 Example 4 3 sccteteschatavtien ene Hae eee ee 4 10 Conf uring a SCS SIOM ensien sonni staves dineBuebeors E R E E E ERE 4 11 ACCeSSING AttriDUtes Seeon a E E E 4 11 Common Considerations for Using Attributes cece ceseeseceeeeeeees 4 11 Chapter 5 Message Based Communication Tntrodu ct Oni
22. Attributes not only describe the state of the device but also the method of communication with the device For example you could use the following code to obtain the logical address of a VXI address status viGetAttribute instr VI_ATTR_VXI_LA amp Laddr and the variable Laddr would contain the device s address If you want to set an attribute such as the baud rate of an ASRL session you could use status viSetAttribute instr VI_ATTR_ASRL_BAUD baudrate Notice that some attributes are read only such as logical address while others are read write attributes such as the baud rate Also some attributes apply only to certain types of sessions VI_ATTR_VXI_LA would not exist for an ASRL device If you attempted to use it the status parameter would return with the code VI_ERROR_NSUP_ATTR Refer to the online help or to the NI VISA Programmer Reference Manual for a list of all available attributes you can use for each supported interface Common Considerations for Using Attributes As you set up your sessions there are some common attributes you can use that will affect how the sessions handle various situations For currently supported session types all support the setting of timeout values and termination methods e VI_ATTR_TMO_VALUE denotes how long in milliseconds to wait for accesses to the device Defaults to two seconds 2000 ms National Instruments Corporation 4 11 NI VISA User Manual Chapter
23. Example 4 2 include visa h As shown in the previous section you can create a session to a resource using the viOpen call However before you use this call you need to know the exact location address of the resource you want to open To find out what resources are currently available at a given point in time you can use the search services provided by the viFindRsrc operation as shown in the following example Notice that while this sample function returns a session it does not return the reference to the resource manager session opened within the same function If you use this style of initialization routine you can get the reference to the resource manager session later by querying the attribute VI_ATTR_RM_SESSION before closing the INSTR session You can then close the resource manager session with viClose define MANF_ID OxFF6 12 bit VXI manufacturer ID of device x define MODEL CODE Ox0FE 12 bit or 16 bit model code of devic aif Find the first matching device and return a session to it AT ViStatus autoConnect ViPSession instrSesn viStatus ViSession ViFindList viChar ViUInt32 ViUInt16 status defaultRM instr fLlist desc VI_FIND_BUFLEN numinstrs iManf iModel status viOpenDefaultRM amp defaultRM if status lt VI_SUCCESS Error initializing VISA exiting return status Find all VXI instruments in the system aA status
24. Instruments Corporation 5 13 NI VISA User Manual Register Based Communication This chapter shows how to use the VISA library in register based communication Note You can skip this chapter if you are using GPIB or serial controllers exclusively Register based programming applies only to VXI or GPIB VXI Introduction Register based devices RBDs are a class of devices that are simple and relatively inexpensive to manufacture Communication with such devices is usually accomplished via reads and writes to registers VISA has the ability to read from and write to individual device registers as well as a block of registers through the Memory I O Services In addition to accessing RBDs VISA also provides support for memory management of the memory exported by a device For example both local controllers and remote devices can have general purpose memory in A24 A32 space With VISA although the user must know how each remote device accesses its own memory the memory management aspects of local controllers are handled through the Shared Memory operations viMemAlloc and viMemFree For more information on this topic refer to the Shared Memory Operations section later in this chapter With the Memory I O Services you access the device registers based on the session to the device In other words if a session communicates with a device at VXI logical address 16 you cannot use Memory I O Services on that session to access reg
25. Rem NOTE For simplicity we will not show error checking stat viOpen df1ltRM VXI0 16 INSTR VI_NULL VI_NULL sesn Rem Enable the driver to detect the interrupts stat viEnableEvent sesn VI_EVENT_VXI_SIGP VI_QUEUE VI_NULL Rem Send the commands to the oscilloscope to capture the Rem waveform and interrupt when done stat viWaitOnEvent sesn VI_EVENT_VXI_SIGP 5000 eType eData If stat lt VI_SUCCESS Then Rem No interrupts received after 5000 ms timeout stat viClose df1tRM Exit Sub End If Rem Obtain the information about the event and then destroy the Rem event In this case we want the status ID from the interrupt stat viGetAttribute eData VI_ATTR_SIGP_STATUS_ID statID stat viClose eData Rem Your code should read data from the instrument and process it Rem Stop listening to events stat viDisableEvent sesn VI_EVENT_VXI_SIGP VI_QUEUE Rem Close down the system stat viClose sesn stat viClose df1tRM End Sub NI VISA User Manual A 4 National Instruments Corporation Appendix A Example 2 4 Private Sub vbMain Const MAX_CNT 200 Dim stat As ViStatus Dim df1ltRM As ViSession Dim sesn As ViSession Dim retCount As Long Dim buffer As String MAX_CNT Rem Begin by initializing the system stat viOpenDefaultRM df1tRM If stat lt VI_SUCCESS Then
26. That is all that is really necessary to perform register I O For more examples of HLA register I O please see Example 2 2 in Chapter 2 Introductory Programming Examples National Instruments Corporation 6 3 NI VISA User Manual Chapter 6 Register Based Communication High Level Block Operations CF Note CF Note NI VISA User Manual The high level block operations viMoveInXX and viMoveOut XX have a simple and easy to use interface for reading and writing blocks of data residing at either the same or consecutive incrementing register addresses Like the high level access operations the high level block operations can detect and handle many errors and do not require calls to the low level mapping operations Unlike the high level access operations the high level block operations do not have a direct low level counterpart To perform block operations using the low level access operations you must map the desired region of memory and then perform multiple viPeek Xx or viPokeXX operation invocations instead of a single call to viMovelInxX or viMoveOut Xx To use the block operations to access a device you need to have the following information about the registers e The address space where the registers are located In a VXI interface for example the address space can be A16 A24 or A32 e The beginning offset of the registers relative to the device for the specified address space You do not need to
27. These functions tell the VISA driver which events to listen for in this case the VI_LEVENT_VXI_SIGP or VXI Signal Processor events These events cover both VXI interrupts and VXI signals In addition these functions tell the driver how to handle the events when they occur In this example the driver is instructed to queue VI_QUEUE the events until asked for them Notice that instr is also supplied to the functions This shows that the VISA driver performs all event handling on a per communication channel basis When the driver is ready to handle events you are free to write code that will result in an event being generated In the example above this is shown as a comment block because the exact code depends on the device However after you have set the device up to interrupt when it is ready the program must wait for the interrupt This is accomplished by the viWaitOnEvent function Here you specify what events you are waiting for and how long you want to wait The program then blocks until the event occurs Therefore after the viWaitOnEvent call is finished either it has timed out 5 s in the above example or it has caught the interrupt After some error checking to determine which case is true and whether it was successful you can obtain information from the event through viGetAttribute When you are finished with the event data structure event Data destroy it by calling viclose on it
28. VI_EVENT_SERVICE_REQ VI_QUEUE VI_NULL Rem Tell the device to begin acquiring a waveform stat viWrite sesn E0Qx51 W1 9 retCount Rem The device asserts SRQ when the waveform is ready stat viWaitOnEvent sesn VI_EVENT_SERVICE_REQ 20000 etype event If stat lt VI_SUCCESS Then Rem Waveform not received exiting stat viClose df1ltRM Exit Sub End If stat viReadSTB sesn stb NI VISA User Manual A 12 National Instruments Corporation Appendix A Visual Basic Examples Rem Read the data stat viRead sesn bufferHandle MAX_CNT retCount Rem Your code should process the waveform data Rem Close the event context stat viClose event Rem Stop listening for events stat viDisableEvent sesn VI_ALL_ENABLED_EVENTS VI_ALL_ MECH Rem Close down the system stat viClose sesn stat viClose df1tRM End Sub National Instruments Corporation A 13 NI VISA User Manual Appendix A Visual Basic Examples Example 8 1 Private Sub vbMain Const MAX_COUNT 128 Dim stat As ViStatus For checking errors Dim dfltRM As ViSession Communication channels Dim sesnIN As ViSession Communication channels Dim sesnOUT As ViSession Communication channels Dim aKey As String VI_FIND_BUFLEN Access key for lock Dim buf As String MAX_COUNT To store device data Dim et
29. VXI to see these devices Windows 95 NT users can configure NI VXI by using the Add Device Wizard in T amp M Explorer Users on other platforms must use the Non VXI Device Editor in VXIedit or VXItedit For each address space in which your device has memory you must create a separate pseudo device entry with a logical address between 256 and 511 For example a VME device with memory in both A24 and A32 spaces requires two entries You can also specify which interrupt levels the device uses VXI and VME devices cannot share interrupt levels You can then access the device from NI VISA just as you would a VXI device by specifying the address space and the offset from the base at which you have configured it NI VISA support for VME devices includes the register access operations both high level and low level and the block move operations as well as the ability to receive interrupts 9 6 National Instruments Corporation Chapter 9 NI VISA Platform Specific and Portability Issues Windows 3 x Issues This section contains information specific to Windows 3 x about the installation and use of NI VISA Installation Overview After the NI VISA driver is installed the Setup program normally makes some modifications to your initialization files AUTOEXEC BAT and WIN INT If you choose not to let the installer make these changes automatically the NI VISA driver may not perform properly The necessary changes include adding
30. You can now continue with the program and retrieve the data The rest of the program is the same as the previous examples Notice the difference in the way you shut down the program if a timeout has occurred You do not need to close the communication channel with the device but only with the VISA driver You can do this because the VISA specification requires that the driver close any channels opened off a channel to the driver defau1tRM when the driver channel is closed As a National Instruments Corporation 2 9 NI VISA User Manual Chapter 2 Introductory Programming Examples result when you need to shut down a program quickly such as in the case of an error you can simply close the channel to the driver and VISA handles the rest of the details for you However VISA does not clean up anything not associated with VISA such as memory you have allocated You are still responsible for those items Example of Locking Example 2 4 include visa h define MAX_CNT 200 int main void Occasionally you may need to prevent other applications from using the same resource that you are using VISA has a service called locking that you can use to gain exclusive access to a resource VISA also has another locking option in which you can have multiple sessions share a lock Because lock sharing is an advanced topic that may involve inter process communication see the Lock Sharing section in Chapter 8 VISA Locks for m
31. access mode and timeout values for viOpen are both VI_NULL Other values are defined but VI_NULL is recommended for both new users and all instrument drivers However notice the statement has two sessions in the parameter list for viOpen defaultR and instr Why do you need two sessions As you will see in a moment viOpen is an operation on a resource known as the Resource Manager so you must have a communication channel to this resource However what you want is a session to the instrument this is what is returned in instr For the entire duration that you communicate with this GPIB instrument you use the session returned in instr as the communication channel When you are finished with the communication you need to close the channel This is accomplished through the viClose operation as shown below status viClose instr National Instruments Corporation 3 9 NI VISA User Manual Chapter 3 VISA Overview At this point the communication channel is closed but you are still free to open it again or open a session to another device Notice that you do not need to close a session to open another session You can have as many sessions to different devices as you want The Resource Manager The previous section briefly mentioned the Resource Manager Resource What exactly is a Resource Manager If you have worked with VXI you are familiar with the VXI Resource Manager Its job is to search the VXI chassis for inst
32. at these examples again but using VISA terminology and focusing more on how they explain the VISA model i Note The examples in this chapter show C source code You can find the same examples in Visual Basic syntax in Appendix A Visual Basic Examples Example of Message Based Communication Serial GPIB and VXI systems all have a definition of message based communication In GPIB and serial the messages are inherent in the design of the bus itself For VXI the messages actually are sent via a protocol known as word serial which is based on register communication In either case the end result is sending or receiving strings Example 2 1 shows the basic steps in any VISA program National Instruments Corporation 2 1 NI VISA User Manual Chapter 2 Introductory Programming Examples Example 2 1 include visa h define MAX_CNT 200 int main void ViStatus status For checking errors ye ViSession defaultRM instr Communication channels y ViUInt32 retCount Return count from string I O ViChar buffer MAX_CNT Buffer for string I O x Begin by initializing the system A status viOpenDefaultRM amp defaultRM if status lt VI_SUCCESS Error Initializing VISA exiting return 1 Open communication with GPIB Device at Primary Addr 1 NOTE For simplicity we will not show error checking af status viOpen defaultRM GPIBO 1 INSTR VI_NULL VI_NULL amp inst
33. communication For example the actual mechanism for sending a byte differs drastically between GPIB and VXI however both have similar mechanisms to indicate when the last byte has been transferred Under both systems a device can specify an actual character such as linefeed to indicate that no more data will be sent This is known as the End Of String EOS character and is common in older GPIB devices The obvious drawback to this mechanism is that you must send an extra character to terminate the communication and you cannot use this character in your messages However both GPIB and VXI can specify that the current byte is the last byte GPIB uses the EOI line on the bus and VXI uses the END bit in the Word Serial command that encapsulates the byte 5 2 National Instruments Corporation Chapter 5 Message Based Communication You need to determine how to inform the driver which mechanism to use As was discussed in Chapter 3 VISA Overview VISA uses a technique known as attributes to hold this information For example to tell the driver to use the EOI line or END bit you set the VI_LATTR_SEND_END_EN attribute to true status viSetAttribute instr VI_ATTR_SEND_END_EN VI_TRU E You can terminate reads on a carriage return by using the following code status viSetAttribute instr VI_ATTR_TERMCHAR_EN VI_TRUE status viSetAttribute instr VI_ATTR_TERMCHAR 0x0D
34. handler queue Independent Queues As stated previously the callback and the queuing mechanisms operate totally independently of each other so VISA keeps the information for event occurrences separately for both mechanisms Therefore VISA maintains the suspended handler queue separately from the event queue used for the queuing mechanism The vI_ATTR_MAX_QUEUE_LENGTH attribute mentioned earlier in the Queuing section of this chapter applies to the suspended handler queue as well as to the queue for the queuing mechanism However because these queues are separate if one of the queues reaches the predefined limit for storing event occurrences it does not directly affect the other mechanism National Instruments Corporation 7 7 NI VISA User Manual Chapter 7 VISA Events The userHandle Parameter When using vilnstallHandler to install handlers for the callback mechanism your application can use the userHandle parameter to supply a reference to any application defined value This reference is passed back to the application as the userHandle parameter to the callback routine during handler invocation By supplying different values for this parameter applications can install the same handler with different application defined contexts For example applications often need information that was received in the callback to be available for the main program In the past this has been done through global variables
35. its operational state Bit Byte National Instruments Corporation G 1 NI VISA User Manual Glossary bus error C callback commander communication channel controller D device DLL event FIFO NI VISA User Manual An error that signals failed access to an address Bus errors occur with low level accesses to memory and usually involve hardware with bus mapping capabilities For example nonexistent memory a nonexistent register or an incorrect device access can cause a bus error Same as handler A software routine that is invoked when an asynchronous event occurs In VISA callbacks can be installed on any session that processes events A device that has the ability to control another device This term can also denote the unique device that has sole control over another device as with the VXI Commander Servant hierarchy The same as session A communication path between a software element and a resource Every communication channel in VISA is unique An entity that can control another device s or is in the process of performing an operation on another device An entity that receives commands from a controller A device can be an instrument a computer acting in a non controller role or a peripheral such as a plotter or printer Dynamic Link Library Same as a shared library or shared object A file containing a collection of functions that can be used by multiple applications This term i
36. know the actual base address of the device just the offset e The number of registers or register values to access The default behavior of the block operations is to access consecutive register addresses However you can change this behavior using the attributes VI_LATTR_SRC_INCREMENT for viMoveInxXX and VI_ATTR_DEST_INCREMENT for viMoveOut XX If the value is changed from 1 the default value indicating consecutive addresses to 0 indicating that registers are to be treated as FIFOs then the block operations performs the specified number of accesses to the same register address The range value of 0 for the VI_ATTR_SRC_INCREMENT and VI_ATTR_DEST_INCREMENT attributes may not be supported on all VISA implementations In this case you may need to perform a manual FIFO block move using individual calls to the high level or low level access operations If you are using the block operations in the default mode consecutive addresses the number of elements that you want to access may not go beyond the end of the device s memory in the specified address space 6 4 National Instruments Corporation Chapter 6 Register Based Communication In other words the following code sample reads the device s entire register set in A16 space status viMovelInl6 instr VI_A16_SPACE 0 0x20 regBufferl 6 Notice that although the device has 0x40 bytes of registers in A
37. lock results in automatically releasing its lock s National Instruments Corporation 8 3 NI VISA User Manual Chapter 8 ic Note Example 8 1 include VISA Locks This example shows C source code You can find the same example in Visual Basic syntax in Appendix A Visual Basic Examples ryasai An define MAX_COUNT 128 int main void ViStatus status For checking errors ViSession defaultRM Communication channels ViSession instrIN instrOUT Communication channels ViChar accKey VI_FIND_BUFLEN Access key for lock ViByte buf MAX_COUNT To store device data af ViEventTyp type To identify event fi ViEvent event To hold event info ViUInt32 retCount To hold byte count xy Begin by initializing the system Ay status viOpenDefaultRM amp defaultRM if status lt VI_SUCCESS Error Initializing VISA exiting ve return 1 Open communications with VXI Device at Logical Addr 16 Ki status viOpen defaultRM VX1I0 16 INSTR VI_NULL VI_NULL amp instrIN status viOpen defaultRM VX1I0 16 INSTR VI_NULL VI_NULL amp instrOUT We open two sessions to the same device One session is used to assert triggers on L channel 4 The second is used to receive triggers on L channel 5 Lock first session as shared have VISA generate the key ad Then lock the
38. operation 5 8 viVPrintf operation 4 8 viVQueryf operation 4 8 viVScanf operation 4 8 viWaitOnEvent operation asynchronous read write services example 4 4 event context 7 11 event queuing process 7 5 programming example 2 3 2 8 2 9 viWrite operation formatted I O operations example 4 8 programming example 2 1 2 4 sending string to device example 3 4 to 3 5 synchronous read write services example 4 2 viWriteAsync operation example 4 4 VME devices NI VISA support for 9 6 VTL specification 1 2 VXI platforms NI VISA support for 9 5 multiple GPIB VXI support 9 5 VXIplug amp play standards 1 2 W Windows 3 x programming issues 9 6 to 9 7 application stack size 9 7 installation overview 9 6 memory model 9 6 word serial protocol 2 1 write services See read write services National Instruments Corporation
39. other than the type of event Therefore by using viGetAttribute on the eventContext parameter as shown in the following code the program can identify the event as a service request status viGetAttribute eventContext VI_ATTR_EVENT_TYPE amp eventType You can retrieve the status byte of the device by issuing a viReadSTB operation This is especially important because on some interfaces such as GPIB it is not always possible to know which device has asserted the service request until a viReadSTB is performed This means that all sessions to devices on the bus with the service request may receive a service request event Therefore you should always check the status byte to ensure that your device was the one that requested service Even if you have only one device asserting a service request you should still call viReadSTB to guarantee delivery of future service request events For example the following code checks the type of event performs a viReadSTB and then checks the result status viGetAttribute eventContext VI_ATTR_EVENT_TYPE amp eventType if eventType VI_EVENT_SERVICE_REQ status viReadSTB instr amp statusByte if status gt VI_SUCCESS amp amp statusByte amp 0x40 Perform action based on Service Request af Otherwise ignore the Service Request vA End IF SRQ NI VISA User Man
40. 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 EXCEPTASSPECIFIEDHEREIN NATIONALINSTRUMENTSMAKESNOW ARRANTIES EXPRESSORIMPLIED ANDSPECIFICALL YDISCLAIMS ANYWARRANTYOFMERCHANTABILITYORFITNESSFORAPARTICULARPURPOSECUSTOMER SRIGHTTORECOVERDAMAGESCAUSED BYFAULTORNEGLIGENCEONTHEPARTOFNATIONALINSTRUMENTSSHALLBELIMITEDTOTH
41. significantly reduces the time and effort involved in programming different interfaces Instead of using a different Application Programmer s Interface API devoted to each interface bus you can use the VISA API whether your system uses a GPIB VXI GPIB VXI PXI or serial controller As an example consider the case of the GPIB VXI controller You can use this device to communicate with VXI devices but through a GPIB cable In other words you use a GPIB interface with GPIB software to send commands to VXI devices There is no way for you to ignore the interface through which you must communicate If you want to access the registers on the VXI device you must use GPIB string communication to ask the GPIB VXI to perform this action Indeed the specification of the GPIB VXI VXI 5 does not even standardize the commands necessary to do this task National Instruments Corporation 3 1 NI VISA User Manual Chapter 3 VISA Overview Objectives of VISA NI VISA User Manual The main objective of the VXIplug amp play Systems Alliance is to increase ease of use for end users of VXI technology through open multivendor VXI systems Instrument programmers need a software architecture that exports the capabilities of the devices not the interface bus In addition they need to be consistent across the devices and interface buses Realizing these goals results in a simpler model to understand and reduces the number of functions the user n
42. such as the termination character attributes An important resource under VISA is the INSTR Resource This resource encapsulates all of the basic device functions together so that you can communicate with the device through a single resource The INSTR Resource exports the most commonly used features of these resources and is sufficient for most instrument drivers Another resource type is the Memory Access or MEMACC Resource The MEMACC Resource allows interface level accesses such as that used by NI VXI but is still independent of the actual interface type National Instruments Corporation 3 7 NI VISA User Manual Chapter 3 VISA Overview Returning to Example 2 1 in Chapter 2 Introductory Programming Examples look at the point where the program has opened a communication channel with a message based device Remember that because of interface independence it does not matter whether the device is GPIB or VXI You want to send the identification query IDN n to the device Because of the possibility that the device or interface could fail you want to ensure that the computer will not hang in the event that no one ever receives the string Therefore the first step is to tell the resource to time out after 5 s 5000 ms status viSetAttribute instr VI_ATTR_TMO_VALUE 5000 You have just set an attribute VI_ATTR_TMO_VALUE of the resource From now on your communication to this resource through this communication chann
43. the VXIbus For example consider an Intel 80x86 based computer running Windows The addresses from 0xD0000 to OxDFFFF 64 KB of addresses do not correspond to any memory You could add an AT MXI board that listens for 0xD0000 to OxDFFFF on the bus and instruct it to map any addresses it finds in this range to the 64 KB of VXI A16 space It does this by taking the OxD off the address so that it has a pure 64 KB address For example 0xDC000 would be mapped to 0xC000 in A16 space which is the base address for a device at Logical Address 0 The same technique is used for other VXI address spaces as well For example if you wanted to access registers at 0x200000 in A24 space you would tell the AT MXI to strip off the OxD as before but this time add 0x200000 to the resulting address and send it out to the VXIbus You may wonder what the difference is between the efficient method and the primitive method They seem to be telling the hardware the same information However there are two important differences In the primitive method the communication described must take place for each access However the efficient method requires only occasional communication with the hardware Only when you want a different address space or an address outside of the window which was 64 KB long in the previous example do you need to reprogram the hardware In addition when you have set up your hardware you can use standard memory access methods such as pointe
44. the serial port before ending the program status viUnlock instr Your code should process the data Close down the system status viClose instr status viClose defaultRM return 0 Example 2 4 Discussion As you can see the program does not differ with respect to controlling the instrument The ability to lock and unlock the resource simply involves inserting the viLock and viUnlock operations around the code that you want to ensure is protected as far as the instrument is concerned To lock a resource you use the viLock operation on the session to the resource Notice that the second parameter is VI_EXCLUSIVE_LOCK This parameter tells VISA that you want this session to be the only session that can access the device The next parameter 5000 is the time in milliseconds you are willing to wait for the lock For example another program may have locked its session to the resource before you Using this timeout feature you can tell your program to wait until either the other program has unlocked the session or 5 s have passed whichever comes first National Instruments Corporation 2 11 NI VISA User Manual Chapter 2 Introductory Programming Examples The final two parameters are used in the lock sharing feature of viLock and are discussed further in Chapter 8 VISA Locks For most applications however these parameters are set to VI_NULL Notice that if the vi Lock call succee
45. to follow these steps 1 Write the address you want 2 Specify the data to send 3 Send the command to perform the access As you can see this method involves a great deal of communication with the local hardware National Instruments Corporation 6 5 NI VISA User Manual Chapter 6 Register Based Communication NI VISA User Manual The National Instruments MXI plug in cards and embedded VXI computers use a second much more efficient method This method involves taking a section of the computer s address space and mapping this space to another space such as the VXI A16 space To understand how mapping works you must first remember that memory and address space are two different things For example most 32 bit CPUs have 4 GB of address space but have memory measured in megabytes This means that the CPU can put out over 23 possible addresses onto the local bus but only a small portion of that corresponds to memory In most cases the memory chips in the computer will respond to these addresses However because there is less memory in the computer than address space National Instruments can add hardware that responds to other addresses This hardware can then modify the address according to the mapping that it has to a VXI address and perform the access on the VXIbus automatically The result is that the computer acts as if it is performing a local access but in reality the access has been mapped out of the computer and to
46. viOpen defaultRM GPIBO 2 INSTR VI_NULL VI_NULL status amp gpibSesn Allocate memory for buffer National Instruments Corporation 7 9 ap NI VISA User Manual Chapter 7 VISA Events In addition allocate space for the ASCII NULL character bufferHandle ViBuf malloc MAX_CNT 1 Tell the driver what function to call on an event status vilInstallHandler gpibSesn VI_EVENT_SERVICE_REQ myCallback bufferHandle Enable the driver to detect events status viEnableEvent gpibSesn VI_EVENT_SERVICE_REQ VI_HNDLR VI_NULL status viEnableEvent gpibSesn VI_EVENT_IO_COMPLETION VI_QUEUE VI_NULL Tell the device to begin acquiring a waveform eh status viWrite gpibSesn E0x51 W1 9 amp retCount The device asserts SRQ when the waveform is ready The callback begins reading the data x After the data is read an I O completion event occurs x status viWaitOnEvent gpibSesn VI_EVENT_IO_COMPLETION 20000 amp etype amp event if status lt VI_SUCCESS Waveform not received exiting X EP bufferHandle viClose defaultRM return 1 Your code should process the waveform data Xf Close the event context viClose event Stop listening for events status viDisableEvent gpibSesn VI_ALL_ENABLED_EVENTS VI_ALL_MECH status viUninstallHandler gpib
47. we will not show error checking stat viOpen df1tR GPIB 1 INSTR VI_NULL VI_NULL sesn Rem Initialize the timeout attribute to 10 s stat viSetAttribute sesn VI_ATTR_TMO_VALUE 10000 Rem Set termination character to carriage return r 0x0D stat viSetAttribute sesn VI_ATTR_TERMCHAR amp HOD stat viSetAttribute sesn VI_ATTR_TERMCHAR_EN VI_TRUE Rem Don t assert END on the last byte stat viSetAttribute sesn VI_ATTR_SEND_END_EN VI_FALSE Rem Clear the devic stat viClear sesn Rem Request the IEEE 488 2 identification information stat viWrite sesn IDN 5 retCount stat viRead sesn idnResult 72 retCount Rem Your code should use idnResult and retCount to parse device info Rem Trigger the device for an instrument reading stat viAssertTrigger sesn VI_TRIG_PROT_DEFAULT Rem Receive results stat viRead sesn resultBuffer 256 retCount Rem Close sessions stat viClose sesn stat viClose df1ltRM End Sub National Instruments Corporation A 9 NI VISA User Manual Appendix A Visual Basic Examples Example 6 1 Sub vbMain Private Dim Dim Dim Dim Dim Dim stat As dfltRM As sesn As addr As mSpace As Value As viStatus ViSession ViSession ViAddr Integer Integer Rem stat TF Open Default Resource Manager viOpenDefaultRM df1tRM stat lt VI_SUCCESS Then Rem Error initializing VISA exiting Sub Exit End If Rem Open Rem NOTE For simplicity stat
48. 1 memory model for NI VISA under Windows 3 x 9 6 message based communication 4 1 to 4 13 basic I O services 4 1 to 4 7 asynchronous read write services 4 3 to 4 4 clear services 4 4 to 4 5 status service request service 4 6 to 4 7 synchronous read write services 4 2 to 4 3 trigger services 4 5 to 4 6 examples example 2 1 2 2 to 2 4 example 4 1 4 12 to 4 13 Visual Basic examples A 2 A 6 formatted I O services 4 7 to 4 11 automatically flushing formatted I O buffers 4 9 to 4 10 controlling serial I O buffers 4 11 formatted I O operations 4 7 to 4 8 NI VISA User Manual Index manually flushing formatted I O buffers 4 9 resizing formatted I O buffers 4 10 variable list operations 4 8 overview 4 1 multiple applications support under NI VISA 9 2 multiple interface support with NI VISA 9 5 to 9 6 multiple GPIB VXI support 9 5 serial port support 9 5 VME support 9 6 VXI and GPIB platforms 9 5 nested locks 8 3 NI VISA See programming considerations for NI VISA VISA 0 object oriented OO design 3 4 operations definition 3 4 P platform specific issues for NI VISA See programming considerations for NI VISA pointer dereferencing vs operations 5 8 manipulating 5 8 to 5 9 portability issues See programming considerations for NI VISA programming considerations for NI VISA 9 1 to 9 4 See also programming with VISA interrupt callback handlers 9 3 to 9 4 low level access function
49. 16 space the fourth parameter is 0x20 Why is this Since the operation accesses 16 bit registers the actual range of registers read is 0x20 accesses times 2 B or all 0x40 bytes When using the block operations to access FIFO registers the number of elements to read or write is not restricted because all accesses are to the same register and never go beyond the end of the device s memory region The following sample code writes 4 KB of data to a device s FIFO register in A16 space at offset 0x10 this offset has no special significance status viSetAttribute instr VI_ATTR_DEST_INCREMENT 0 status viMoveOut32 instr VI_A16_SPACE 0x10 1024 regBuffer32 Low Level Access Operations Low Level Access LLA operations provide a very efficient way to perform register based communication LLA operations incur much less overhead than HLA operations for certain types of accesses LLA operations perform the same steps that the HLA operations do except that each individual task performed by an HLA operation is an individual operation under LLA Overview of Register Accesses from Computers Before learning about the LLA operations first consider how a computer can perform a register access to an external device There are two possible ways to perform this access The first and more obvious although primitive is to have some hardware on the computer that communicates with the external device You would have
50. 7 3 VISA event model 7 1 examples See programming examples exclusive locks 8 1 8 3 See also locks F fax and telephone support B 2 FaxBack support B 2 flushing buffers See buffers formatted I O services 4 7 to 4 11 automatically flushing formatted I O buffers 4 9 to 4 10 controlling serial I O buffers 4 11 formatted I O operations 4 7 to 4 8 manually flushing formatted I O buffers 4 9 resizing formatted I O buffers 4 10 Variable List operations 4 8 NI VISA User Manual l 2 framework definition 1 2 framework and programming language support table 1 3 to 1 4 FTP support B 1 G global attributes 3 5 GPIB platforms NI VISA support for 9 5 multiple GPIB VXI support 9 5 H High Level Access operations 5 2 to 5 3 comparison of high and low level access 5 10 to 5 11 accessing multiple address spaces 5 11 ease of use 5 10 speed 5 10 read and write operations table 5 2 register based communication 3 7 to 3 8 high level block operations read and write operations table 5 2 register based communication 5 4 to 5 5 INSTR Resource definition 3 4 instrument drivers 3 3 interface independence GPIB example 3 8 to 3 9 interface support with NI VISA See multiple interface support with NI VISA interface level triggering 4 6 interrupt callback handlers 9 3 to 9 4 T O completion event 4 3 to 4 4 asynchronous read write services 4 3 to 4 4 enabling note 4 3 National Instrument
51. 96 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 512 794 5678 National Instruments Corporation Technical Support Form Photocopy this form and update it each time you make changes to your software or hardware and use the completed copy of this form as a reference for your current configuration Completing this form accurately before contacting National Instruments for technical support helps our applications engineers answer your questions more efficiently If you are using any National Instruments hardware or software products related to this problem include the configuration forms from their user manuals Include additional pages if necessary Name Company Address Fax Phone Computer brand Model Processor Operating system include version number Clock speed MHz RAM MB Display adapter Mouse ___ yes ___no___ Other adapters installed Hard disk capacity MB Brand Instruments used National Instruments hardware product model Revision Configuration National Instruments software product Version Configuration The problem is List any error messages The following steps reproduce the problem Documentation Comment Form National Instruments encourages you to comment on the documentation supplied with our products This information helps us pro
52. Although the macros can increase performance only on NI VISA your application will be binary compatible with other implementations of VISA the macros will just call the viPeekxXx and viPokeXX operations However the macros are not enabled by default To use the macros you must define the symbol NIVISA_PEEKPOKE before including visa h Interrupt Callback Handlers Application callbacks available in C but not in LabVIEW or Visual Basic are registered with the vilnstallHandler operation and must be declared with the following signature ViStatus _VI_FUNCH appHandler ViSession vi ViEventTyp ventType ViEvent event ViAddr userHandle Notice that the _VI_FUNCH modifier expands to_far _pascal for Windows 3 x 16 bit and _stdca11 for Windows 95 and Windows NT 32 bit These are the standard Windows callback definitions On other systems such as UNIX and Macintosh VISA defines _VI_FUNCH to be nothing null Using _VI_FUNCH for handlers makes your source code portable to systems that need other modifiers or none at all After you install an interrupt handler and enable the appropriate event s an event occurrence causes VISA to invoke the callback When VISA invokes an application callback it does so in the correct application context From within any handler you can call back into the NI VISA driver On all platforms other than Macintosh you can also make system calls The way VISA invokes callback
53. EAMOUNTTHERETOFOREPAIDB YTHE CUSTOMER NATIONALINSTRUMENTSWILLNOTBELIABLEFORDAMAGESRESULTINGFROMLOSSOFDATA PROFITS USEOFPRODUCTS ORINCIDENTALORCONSEQUENTIALDAMAGES EVENIFADVISEDOFTHEPOSSIBILITY THEREOF Thislimitationoftheliability 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 owner s failure to follow the National Instruments installation operation or maintenance instructions owner s modification of the product owner s abuse misuse or negligent acts and power failure or surges fire flood accident actions of third parties or other events outside reasonable control 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 CVI LabVIEW NI 488 2 NI VISA NI VXI and VXIpc are trademarks of National Instruments Corporation Product and company names listed are trademarks or trade nam
54. E_ERROR If the error occurs during the operation itself the status is returned as part of the VI_EVENT_IO_COMPLETION event This is important because that event may occur in a separate thread due to the nature of asynchronous I O Therefore you should not use asynchronous operations if you wish to throw C exceptions from your handler National Instruments Corporation 7 13 NI VISA User Manual VISA Locks Introduction This chapter describes how to use locks in VISA Lock Types VISA introduces locks for access control of resources In VISA applications can open multiple sessions to a resource simultaneously and can access the resource through these different sessions concurrently In some cases applications accessing a resource must restrict other sessions from accessing that resource For example an application may need to execute a write and a read operation as a single step so that no other operations intervene between the write and read operations The application can lock the resource before invoking the write operation and unlock it after the read operation to execute them as a single step VISA defines a locking mechanism to restrict accesses to resources for such special circumstances The VISA locking mechanism enforces arbitration of accesses to resources on an individual basis If a session locks a resource operations invoked by other sessions are serviced or returned with a
55. IB with VXI Again remember that the difference in the address string name is the extent to which the specific interface bus will be important Indeed since this is a simple string it is possible to have the program read in the string from a user input or a configuration file Thus the program can be compiled and is still portable to different platforms such as from a GPIB VXI to a MXIbus board As you can see from the programming code you use different functions to perform I O with a register based device The functions viIn16 and viOut16 read and write 16 bit values to registers in either the A16 A24 or A32 space of VXI As with the message based functions you start by specifying which device you want to talk to by supplying the instr variable You then identify the address space you are targeting such as VI_A16_SPACE The next parameter warrants close examination Notice that we want to read in the value of the Device ID register for the device at logical address 16 Logical addresses start at offset 0xC000 in A16 space and each logical address gets 0x40 bytes of address space Because the Device ID register is the first address within that 0x40 bytes the absolute address of the Device ID register for logical address 16 is calculated as follows OxCO00 0x40 16 0xC400 However notice that the offset we supplied was 0 The reason for this is that the instr parameter identifies which device you are talking to and therefo
56. PIB device telling it to read some data When the data collection is complete the device asserts SRQ informing the program that it can now read data After reading the device s status byte the handler begins to read asynchronously using a buffer of information that the main program passes to it 7 8 National Instruments Corporation cop Note Example 7 1 Chapter 7 VISA Events This example shows C source code You can find the same example in Visual Basic syntax in Appendix A Visual Basic Examples include visa h include lt stdlib h gt define MAX_CNT 1024 This function is to be called when an SRQ event occurs Here an SRQ event indicates the device has data ready y f ViStatus _VI_FUNCH myCallback ViSession vi ViEventType etype ViJobId jo ViStatus st ViUInt16 st status status return ViEvent event ViAddr userHandle bID atus b viReadSTB vi amp sthb viReadAsync vi ViBuf userHandle MAX_CNT amp jobID VI_SUCCI int main void ViStatus st ViSession de ViBuf bu ViUInt32 re ViEventType et ViEvent ev ESS atus faultRM gpibSesn fferHandle tCount ype ent Begin by initializing the system status J vidOpenDefaultRM amp defaultRM if status lt VI_SUCCESS Error in return 1 itializing VISA exiting ay af Open communication with GPIB device at primary address 2
57. PIB messages are necessary is no longer important you can let the driver take care of those details Program your instrument based on its capabilities 3 12 National Instruments Corporation Initializing Your VISA Application This chapter describes the steps required to prepare your application for communication with your device Introduction A powerful feature of VISA is the concept of a single interface for finding and accessing devices on various platforms The VISA Resource Manager does this by exporting services for controlling and managing resources These services include but are not limited to assigning unique resource addresses and unique resource IDs locating resources and creating sessions Each session contains all the information necessary to configure the communication channel with a device as well as information about the device itself This information is encapsulated inside a generic structure called an attribute You can use the attributes to configure a session or to find a particular resource Opening a Session When trying to access any of the VISA resources the first step is to get a reference to the default Resource Manager by calling viOpenDefaultRM Your application can then use the session returned from this call to open sessions to resources controlled by that Resource Manager as shown in the following example Note The examples in this chapter show C source code You can find the s
58. Read viln8 viMovelIn8 viPeeks8 vitInl6 viMovelInl16 viPeek16 vilIn32 viMoveln32 viPeek32 Write viOuts8 viMoveOut 8 viPokes viOut16 viMoveOut16 viPokel 6 vi0ut32 viMoveOut 32 viPoke32 The remainder of this chapter uses Xx in the names of some operations to denote that the information applies to 8 bit 16 bit and 32 bit reads and writes For example vilnXX refers to viln8 viln16 and viln32 The following sections show the benefits of each style so you can make an informed choice of which is more appropriate for your programming requirements High Level Access Operations NI VISA User Manual The High Level Access HLA operations viInxx and viOut xXx have a simple and easy to use interface for performing register based communication The HLA operations in VISA are wholly self contained in that all the information necessary to carry out the operation is contained in the parameters of the operation The HLA operations also perform all the necessary hardware setup as well as the error detection and handling There is no need to call other operations to do any other activity related to the register access For this reason you should use HLA operations if you are just becoming familiar with the system 6 2 National Instruments Corporation Chapter 6 Register Based Communication To use vilnXX or viOut XX operations to access a register on a device you need t
59. See the description of the viFlush operation in the NI VISA online help or in the NI VISA Programmer Reference Manual for more information Automatically Flushing the Formatted 1 0 Buffers Although you can explicitly flush the buffers by making a call to viF lush the buffers are flushed implicitly under some conditions These conditions vary for the viPrintf and viScanf operations In addition you can modify the conditions through attributes The write buffer is maintained by the viPrintf vivPrintf viBufWrite and vivQueryf write side operations To explicitly flush the write buffer you can make a call to the viF lush operation with a write flag set National Instruments Corporation 5 9 NI VISA User Manual Chapter 5 Message Based Communication The standard conditions for automatically flushing the buffer are as follows Whenever the END indicator is sent The indicator could be either the EOS character or the END bit EOI line depending on the current state of the attributes which select these modes e When the write buffer is full e Inresponse to acall to viSetBuf with the VI_WRITE_BUF flag set In addition to these rules the VI_ATTR_WR_BUF_OPER_MODE attribute can modify the flushing of the buffer The default setting for this attribute is VI_FLUSH_WHEN_FULL which means that the preceding three rules apply However if the attribute is set to VI_FLUSH_ON_ACCESS the buffer i
60. Sesn VI_EVENT_SERVICE_REQ myCallback bufferHandle Close down the system fr bufferHandle status viClose gpibSesn status viClose defaultRM return 0 NI VISA User Manual 7 10 National Instruments Corporation Chapter 7 VISA Events The Life of the Event Context The event context that the VISA driver generates when an event occurs is a data object that contains the information about the event Because it is more than just a simple variable memory allocation and deallocation becomes important Event Context with the Queuing Mechanism When you use the queuing mechanism the event context is returned when you call viWaitOnEvent The driver has created this data structure but it cannot destroy it until you tell it to For this reason in VISA you call viClose onthe event context so the driver can free the memory for you Always remember to call viClose when you are done with the event If you know the type of event you are receiving and the event does not provide any useful information to your application other than whether it actually occurred you can pass VI_NULL as the outEventType and eventContext parameters as shown in the following example status viWaitOnEvent gpibSesn VI_EVENT_SERVICE_REQ 5000 VI_NULL VI_NULL In this case VISA automatically closes the event data structure rather than returning it to you cal
61. T 8 3 Example 8 lea ea ea ieee tue Nebo E A E OESE 8 4 Chapter 9 NI VISA Platform Specific and Portability Issues Programming Considerations 0 eet eecesecesceeceeeeeeceseeesecaeecaeceaeeaeceeceseceseeseeeeeeseeeeeeas 9 2 Debugging Tool for Windows 95 NT uo ee ceceseceeceseeeeceeeeeeeeseeeseeseeeaeesaesaes 9 2 Multiple Applications Using the NI VISA Driver eee eee cereeeeeeeees 9 2 Low Level Access Functions eneen r a E E EEN 9 2 Interrupt Callback Handlers sseeeseeeeeseeeeseeeeerseeeseseerssrsresrserrenrerrsreresreness 9 3 Multiple Interface Support Issues seeeesseeeseseeeeseeereerssresssrsresreresresrerrseeresenresrseesresee 9 5 VXI and GPIB Platforms 2 3 sss naa E E e 9 5 Multiple GPIB VXI SUPOT iesise a E 9 5 Serial Port SUPPOTt nse eepe re E E a E ERS eS 9 5 VME SUPPOLt iscessos 28 aee ees eese arees menes sa vevoot tus speesasuvsdvevgurdedderesstlecoeysavsheeetes 9 6 Windows 3 X ISSUES h aner pa EEEE A EEE EE EE A EEE RE 9 7 Installation OVervi EW ini toa ia EEE N EE 9 7 Memory Modelinin i E EEE EA O TE 9 7 Application Stack Size ieni irn e E i p as 9 7 Appendix A Visual Basic Examples Appendix B Customer Communication Glossary Index Tables Table 1 1 NEVISASUpPPOLt AA E E E EEE 1 3 Table 9 1 How VISA Invokes Callbacks s ssssesseeeeesessssesseessesssrssrrsersressrssressessees 9 4 Table 9 2 How Serial Ports Are Numbered ss nssseseeseeeseseeseseeseseerereseersesseeserssress 9 6 NI VISA User Ma
62. This Manual seori terep ns easar eke r EErEE EEE Eii 1 1 What You Need to Get Started oo ceeesecseecsecseeaecsecaececeseesesneeseseaeeeeseaseneeeaes 1 1 Introduction to VISA ii s ssss escce seeks see sogs dak os sse eds vge thoes des ey tbnahdivedsassssssnastoasegvasbiensdesnescoes 1 2 Chapter 2 Introductory Programming Examples Example of Message Based Communication 00 cc ceceeecssessecsecesecneceseeneceseeereeeeeeeeees 2 1 Example 2 i wcitiecitvdeeiiinsiinistencdiaaiieeian eedeeegacenteee steels E S Nan 2 2 Example 21 DiSCussiOn ninnan nn nein hens e E ener darrecneas sees 2 3 Example of Register Based Communication ceeececeeeeeeeeceeeeeeeeneeeneeseecaecnaeenees 2 4 EXAMple 2 2 e e T E a a E ce aveuneetdpalpantoreess EEIN 2 5 Example 2 2 Discussion sseeeessesessesesrssseresetrrsreetsresrerreeereserersrnesrsreseesene 2 6 Example of Handling Events ac enoo e O OERE ECE RR 2 7 Callbacks ea aA eee E E a ihe ee 2 7 QUEUING PAE EEE EO AE EEE ET EEEE E AE EEEE 2 7 Example 223 sis nie in di Se teens hae a eS E ES 2 8 Example 2 3 DISCUSSION misrani toni seated eck oeeeiaay tees E E SS 2 9 Example of bochna eE eee ie Sieg A ARE ESS 2 10 Example 274 es csste cd scevteeds das cuasssye deeded a e a a A 2 10 Example 2 4 Discussion cesccssccesseceececeseecsseeeececeeeeneceseeceaeceseeeeeeeaeeeneeeees 2 11 Chapter 3 VISA Overview Introd CEI ioni e E RET RTEA E A AEE 3 1 Objectives of VISAS da Mie tl ie a E A A Be
63. VISA NI VISA User Manual 7 NATIONAL June 1998 Editi WiNsTRUMENTS Part Number 321074D 01 Internet Support E mail support natinst com FTP Site ftp natinst com Web Address www natinst com Bulletin Board Support BBS United States 512 794 5422 BBS United Kingdom 01635 551422 BBS France 01 48 65 15 59 Fax on Demand Support 512418 1111 Telephone Support USA Tel 512 795 8248 Fax 512 794 5678 International Offices Australia 03 9879 5166 Austria 0662 45 79 90 0 Belgium 02 757 00 20 Brazil 011 288 3336 Canada Ontario 905 785 0085 Canada Qu bec 514 694 8521 Denmark 45 76 26 00 Finland 09 725 725 11 France 01 48 14 24 24 Germany 089 741 31 30 Hong Kong 2645 3186 Israel 03 6120092 Italy 02 413091 Japan 03 5472 2970 Korea 02 596 7456 Mexico 5 520 2635 Netherlands 0348 433466 Norway 32 84 84 00 Singapore 2265886 Spain 91 640 0085 Sweden 08 730 49 70 Switzerland 056 200 51 51 Taiwan 02 377 1200 United Kingdom 01635 523545 National Instruments Corporate Headquarters 6504 Bridge Point Parkway Austin Texas 78730 5039 USA Tel 512 794 0100 Copyright 1996 1998 National Instruments Corporation All rights reserved Important Information Copyright Trademarks 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
64. V_INTR_LEVEL Which provide the interrupt status and interrupt level respectively e VI_EVENT_EXCEPTION defines VI_ATTR_STATUS and VI_ATTR_OPER_NAME which provide information about what error was generated and which operation generated it respectively All the attributes VISA events support are read only attributes a user application cannot modify their values Refer to the NI VISA online help or to the NI VISA Programmer Reference Manual for detailed information on the specific events Enabling and Disabling Events Before a session can use either the VISA callback or queuing mechanism you need to enable the session to sense events You can use the viEnableEvent operation to enable an event using either of the mechanisms You can also enable events using a combination of both queuing and callback mechanisms by bit wise ORing together the different mechanisms For example to enable the VI_EVENT_VXI_SIGP event for queuing use the following code status viEnableEvent instr VI_EVENT_VXI_SIGP VI_QUEUE VI_NULL However to enable the same event for both queuing and callbacks change the code as follows status viEnableEvent instr VI_EVENT_VXI_SIGP VI_QUEUE VI_HNDLR VI_NULL National Instruments Corporation 7 3 NI VISA User Manual Chapter 7 VISA Event
65. a pointer dereference to perform register accesses on a given mapped session examine the value of the VI_LATTR_WIN_ACCESS attribute If the value is VI_DEREF_ADDR it is safe to perform a pointer dereference To make your code portable across different platforms we recommend that you always use the accessor operations viPeekxXx and viPokeXx as a backup method to perform register I O In this way not only is your source code portable but your executable can also have binary compatibility across different hardware platforms even on systems that do not support direct pointer dereferences viGetAttribute instr VI_ATTR_WIN_ACCESS amp access j if access VI_DEREF_ADDR address 0x1234 else viPokel6 instr address 0x1234 Manipulating the Pointer Every time you call viMapAddress the pointer you get back is valid for accessing a region of addresses Therefore if you call viMapAddress with mapBase Set to address 0 and mapSize to 0x40 the configuration register space for a VXI device you can access not only the register located at address 0 but also registers in the same vicinity by manipulating the pointer returned by viMapAddress For example if you want to access another register at address 0x2 you can add 2 to the pointer You can add up to and including 0x3F to the pointer to access these registers in this example because we have specified 0x40 as the map size However not
66. ac deamon sewn 7 1 Supported Events sne y wee ale hehe AI aie hie BEA RE 7 2 Enabling and Disabling Events cece eeeeseeseeceecaeecaecseaeceeceseceeeeseeeseeeeeeseaeeees 7 3 QUEUING vse sel Meee LEN a ee a Ie aes ee eee R E 7 4 Callbacks eeunet n E E T TRR soba ores A RI 7 6 Callback Modes i urren nA E E E ee tek ae oes 7 6 Independent Quete Se innn a e n en 7 7 The userHandle Parameter ecceessseeeceesecesseceececeseeenceeeneecseceeaeceseecsaeceeeees 7 8 Queuing and Callback Mechanism Sample Code esececeseceeeeseeeeeeeeeeeeeneeees 7 8 Example d ing tve sis talon Bad eee Rw tee as IR 7 9 The Life of the Event Context drainn n a eae 7 11 Event Context with the Queuing Mechanism eee ee ceeeeeeeeeeeeeeeeeeees 7 11 Event Context with the Callback Mechanism cecccesesssecenceceeeeeneeeeneenes 7 11 Exception Handling c secscccsscceecseepenevectestecnssecpevenssvs tooo vaecvasesnsepenbendaaevedocedenptovceesentents 7 12 Chapter 8 VISA Locks TTtHOGUCTLON ssori n Muedosusetsvedou toseveccevertecdeceueesdsds sdhdePasadectleotesededdeceeeddges 8 1 LOCK VY a EE ieee aetna a ee eS 8 1 National Instruments Corporation vil NI VISA User Manual Contents Lock SHAM 8 iccoco ces eoe lata eb ckn o a Gos nies Ate seb EEEO I Ea Eee 8 2 Acquiring an Exclusive Lock While Owning a Shared Lock 8 3 Nest d COCKS orietan n etal E E aE sth ceavten soe dameseueey S R S 8 3 Locking Sample Codeine Eaa r EA EEE EE EEEE E RE TE
67. ame examples in Visual Basic syntax in Appendix A Visual Basic Examples National Instruments Corporation 4 1 NI VISA User Manual Chapter 4 Initializing Your VISA Application Example 4 1 include visa h int main void ViStatus status ViSession defaultRM instr Open Default RM X7 status viOpenDefaultRM amp defaultRM if status lt VI_SUCCESS Error Initializing VISA exiting ef return 1 Access other resources 7 status viOpen defaultRM GPIB 1 INSTR VI_NULL VI_NULL amp instr Use device and eventually close it xy viClose instr viClose defaultRM return 0 As shown in this example you use the viOpen call to open new sessions In this call you specify which resource to access by using a string that describes the resource The following table shows the format for this string Square brackets indicate optional string segments Interface Syntax VXI VXI board VXI logical address INSTR GPIB VXI GPIB VXI board VXI logical address INSTR GPIB GPIB board primary address secondary address INSTR ASRL ASRL board INSTR VXI VXI board MEMACC GPIB VXI GPIB VXI board MEMACC NI VISA User Manual 4 2 National Instruments Corporation Chapter 4 Initializing Your VISA Application Use the VXI keyword for VXI instruments via either embedded or MXIbus controllers Use the GPIB V XI keywo
68. ation 9 1 NI VISA User Manual Chapter 9 NI VISA Platform Specific and Portability Issues Programming Considerations This section contains information for you to consider when developing applications that use the NI VISA I O interface software Debugging Tool for Windows 95 NT NI Spy tracks the calls your application makes to National Instruments test and measurement T amp M drivers including NI VXI NI VISA and NI 488 2 NI 488 2 users may notice that NI Spy is similar to GPIB Spy NI Spy highlights functions that return errors so you can quickly determine which functions failed during your development NI Spy can also log your program s calls to these drivers so you can check them for errors at your convenience Multiple Applications Using the NI VISA Driver Multiple application support is an important feature in all implementations of the NI VISA driver You can have several applications that use NI VISA running simultaneously You can even have multiple instances of the same application that uses the NI VISA driver running simultaneously if your application is designed for this The NI VISA operations perform in the same manner whether you have only one application or several applications or several instances of an application all trying to use the NI VISA driver However you need to be careful when you have multiple applications or sessions using the low level VXIbus access functions The memory windows used to acce
69. ave secondary addresses from to 9 ASRL INSTR VI_ATTR_ASRL_BAUD 9600 Find all serial ports configured at 9600 baud VXI INSTR VI_ATTR_MANF_ID OxFF6 amp amp VI_LATTR_VXI_LA VI_ATTR_SLOT lt 0 Find all VXI instrument resources with manufacturer ID of FF6 and which are not logical address 0 slot 0 or external controllers Notice that only global VISA attributes are permitted in the attribute matching expression The following example is similar to Example 4 2 except that it uses a regular expression with attribute matching Notice that because only the first match is needed VI_NULL is passed for both the retCount and findList parameters This tells VISA to automatically close the find list rather than return it to the application National Instruments Corporation 4 9 NI VISA User Manual Chapter 4 Initializing Your VISA Application Example 4 3 include lt stdio h gt include visa h define MANF_ID define MODEL CODE Find the ViStatus au NI VISA User Manual Ox0OFE ViStatus status ViSession defaultRM instr ViChar desc VI_FIND_BUFLEN OxFF6 12 bit VXI manufacturer ID of device 12 bit or 16 bit model cod of devic first matching device and return a session to it toConnect2 ViPSession instrSesn regExToUse VI_FIND_BUFLEN status viOpenDefaultRM amp defaultRM if status lt VI_SUCCESS
70. bout the specific occurrence of the event Refer to the section The Life of the Event Context later in this chapter for more information on event context You can now have multiple handlers per session in the current revision of VISA If you have multiple handlers installed for the same event type on the same session each handler is invoked on every occurrence of that event type The handlers are invoked in reverse order of installation that is in Last In First Out LIFO order For a given handler to prevent other handlers on the same session from being executed it should return the value VI_SUCCESS_NCHAIN rather than VI_SUCCESS This does not affect the invocation of event handlers on other sessions or in other processes VISA gives you the choice of two different modes for using the callback mechanism You can use either direct callbacks or suspended callbacks You can have only one of these callback modes enabled at any one time To use the direct callback mode specify VI_HNDLR in the mechanism parameter In this mode VISA invokes the callback routine at the time the event occurs To use the suspended callback mode specify vI_SUSPEND_HNDLR in the mechanism parameter In this mode VISA does not invoke the callback routine at the time of event occurrence instead the events are placed on a suspended handler queue This queue is similar to the queue used by the 7 6 National Instruments Corporation Chapter 7 VISA Event
71. ch for a resource based on the values of the resource s attributes The viFindRsrc search expression is handled in two parts the regular expression for the resource string and the optional logical expression for the attributes Assuming that a given resource matches the given regular expression VISA checks the attribute expression for a match The resource matches the overall string if it matches both parts Attribute matching works by using familiar constructs of logical operations such as AND amp amp OR and NOT Equal and unequal apply to all types of attributes and you can additionally compare numerical attributes using other common comparators gt lt gt and lt 4 8 National Instruments Corporation Chapter 4 Initializing Your VISA Application You are free to make attribute matching expressions as complex as you like using multiple ANDs ORs and NOTs Precedence applies as follows e The grouping operator in an attribute matching expression has the highest precedence e The NOT operator has the next highest precedence e The AND operator has the next highest precedence e The OR operator has the lowest precedence The following table shows three examples of matching based on attributes Expression Meaning GPIB 0 9 INSTR VI_ATTR_GPIB_SECONDARY_ADDR gt 0 amp amp VI_ATTR_GPIB_SECONDARY_ADDR lt 10 Find all GPIB devices that h
72. cification e VPP 3 4 Instrument Driver Programmatic Developer Interface Specification e VPP 4 3 The VISA Library e VPP 4 3 2 VISA Implementation Specification for Textual Languages e VPP 4 3 3 VISA Implementation Specification for the G Language e VPP 5 VXI Component Knowledge Base Specification e VPP 6 Installation and Packaging Specification e VPP 7 Soft Front Panel Specification e VPP 8 VXI Module Mainframe to Receiver Interconnection e VPP 9 Instrument Vendor Abbreviations 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 configuration forms for you to complete These forms are in Appendix B Customer Communication at the end of this manual NI VISA User Manual xii National Instruments Corporation Introduction This chapter discusses how to use this manual lists what you need to get started and contains a brief description of the VISA Library The National Instruments implementation of VISA is known as NI VISA How to Use This Manual This manual provides a sequential introduction to setting up a system to use VISA and then using and programming the environment Please gather all the components described in the next section What You Need to Get Sta
73. d example using asynchronous I O see Example 7 1 in Chapter 7 VISA Events F Note The asynchronous I O services are not available when programming with Visual Basic Clear Service NI VISA User Manual When communicating with a message based device particularly when you are first developing your program you may need to tell the device to clear its I O buffers so that you can start again In addition if a device has more information than you need you may want to read until you have everything you need and then tell the device to throw the rest away The viClear operation performs these tasks More specifically the clear operation lets a controller send the device clear command to the device it is associated with as specified by the interface specification and the type of device The action that the device takes depends on the interface to which it is connected e For a GPIB device the controller sends the IEEE 488 1 SDC 04h command e Fora VXI or MXI device the controller sends the Word Serial Clear FFFFh command e Fora serial device the controller sends the string CLS n The I O protocol must be set to VI_ASRL_488 for this service to be available to serial devices 5 4 National Instruments Corporation Chapter 5 Message Based Communication For more details on these clear commands refer to your device documentation the IEEE 488 1 standard or the VXIbus specification Trigger Service Most instrumen
74. deliberately avoided using VISA terminology to show that writing programs under VISA can be very straightforward and similar to software drivers you have used in the past This section looks at these examples again but this time from the perspective of the underlying architecture Beginning Terminology Let us begin by defining some terminology Typical device capabilities include sending and receiving messages responding to register accesses requesting service being reset and so on One of the underlying premises of VISA as defined in the previous section is to export the capabilities of the devices independent of the interface bus to the user Therefore when creating the building blocks for VISA it is important to focus on these basic device capabilities VISA encapsulates each of these abilities into a resource A resource is simply a complete description of a particular set of capabilities of a device For example to be able to write to a device you need a function you can use to send messages viWrite In addition there are certain details you need to consider such as what the termination character is if any and how long the function should try to communicate before timing out Those of you familiar with this methodology might recognize this approach as object oriented OO design Indeed VISA is based on OO design In keeping with the terminology of OO we call the functions of these resources operations and the details
75. ds you then have exclusive access to the device Other programs do not have access to the device at all Therefore you should hold a lock only for the time you need to program the device especially if you are designing a VXIplug amp play instrument driver Failure to do so may cause other applications to block or terminate with a failure To end the example the application calls viUnlock when it has acquired the data from the instrument At this point the resource is accessible from any other session in any application NI VISA User Manual 2 12 National Instruments Corporation VISA Overview This chapter contains an overview of the VISA Library Introduction The history of instrumentation reached a milestone with the ability to communicate with an instrument from a remote computer Before this time you had to perform data collection and analysis manually through the controls on the instrument s front panel Controlling instruments programmably brought a great deal of power and flexibility with the capability to control devices faster and more accurately without the need for human supervision As time went on the substantial programming task was alleviated by application development environments such as LabVIEW and LabWindows CVI These applications increased productivity but instrumentation system developers were still faced with the details of programming the instrument or the device interface bus The VISA Library
76. ects and exits Notice that in this code segment the event object is closed inside of the callback even though we just recommended in the previous section that you not do this The reason that we do it here is that the code will never return control to VISA calling exit will return control to the operation system instead This is the only case where you should ever invoke viClose within a callback Another more advanced use of this event type is for throwing C exceptions Because VISA exception event handlers are invoked in the context of the same thread in which the error condition occurs you can safely throw a C exception from the VISA handler Like the example above you would invoke viClose on the exception event but you would probably not close the actual session or its resource manager session You would also need to include the information about the VISA exception for example the status code in your own exception class of the type that you throw since this will not be available once the VISA event is closed Throwing C exceptions introduces several issues to consider First if you have mixed C and C code in your application this could introduce memory leaks in cases where C functions allocate local memory on the heap rather than the stack Second if you use asynchronous operations an exception is thrown only if the error occurs before the operation is posted for example if the error generated is VI_ERROR_QUEU
77. ed lock can also be useful when one of the sessions needs to execute in a critical section Nested Locks VISA supports nested locking That is a session can lock the same resource multiple times for the same lock type Unlocking the resource requires an equal number of invocations of the viUnlock operation Each session maintains a separate lock count for each type of locks Repeated invocations of the viLock operation for the same session increase the appropriate lock count depending on the type of lock requested In the case of shared locks nesting viLock calls return with the same accessKey every time In the case of exclusive locks viLock does not return an accessKey regardless of whether it is nested For each invocation of viUnlock the lock count is decremented VISA unlocks a resource only when the lock count equals 0 Locking Sample Code Example 8 1 uses a shared lock because two sessions are opened for performing trigger operations The first session receives triggers and the second session sources triggers A shared lock is needed because an exclusive lock would prohibit the other session from accessing the same resource If viWaitOnEvent fails this example performs a viClose on the resource manager without unlocking or closing the sessions When the resource manager session closes all sessions that were opened using it automatically close as well Likewise remember that closing a session that has any
78. ee operation programming example 5 13 shared memory operation 5 11 viMoveln8 viMoveln16 viMoveIn32 operations 5 4 to 5 5 viMoveOut8 viMoveOut16 viMoveOut32 operations 5 4 to 5 5 viOpen operation creating session for resource example 6 2 opening communication channels example 3 5 to 3 6 programming example 2 2 2 3 6 2 viOpenDefaultRM operation programming example 2 2 2 3 6 2 starting sessions 3 6 to 3 7 6 2 viOut8 viOut16 viOut32 operations High Level Access operations 5 2 to 5 3 interface independence example 3 9 programming example 2 2 2 5 2 6 National Instruments Corporation l 7 Index writing to memory location example 3 7 to 3 8 viPeek8 viPeek16 viPeek32 operations 5 8 9 2 viPoke8 viPoke16 viPoke32 operations 5 8 9 2 viPrintf operation automatically flushing formatted I O buffers 4 9 formatted I O operations 4 7 manually flushing formatted I O buffers 4 9 viQueryf operation 4 8 viRead operation reading string from device example 3 5 synchronous read write services example 4 2 viReadSTB operation 4 6 Virtual Instrument Software Architecture See VISA VISA background and history 1 2 to 1 4 3 1 framework and programming language support table 1 3 to 1 4 objectives 3 2 to 3 3 requirements for getting started 1 1 standards for VXIplug amp play software 1 2 VISA API 3 1 VISA Resource Manager 6 1 to 6 6 accessing resources 6 1 to 6 3 address string
79. eeds to learn Using the example of the GPIB VXI a software driver that satisfies these goals should be capable of sending and receiving messages string communication to and from message based devices In addition the communication functions should be the same regardless of the interface through which these messages are sent Any functionality that the device exports such as message or register communication should be accessible regardless of the capabilities of the interface bus Moreover you should be able to access this functionality through the same functions regardless of the interface bus you are using With the vast number of choices in instrumentation and software now available most users do not want to be limited to a specific vendor for their systems Instead they prefer the freedom to select the best instruments and software available from multiple vendors and have it all work together with minimal effort The IEEE 488 1 and IEEE 488 2 standards for GPIB and the IEEE 1155 standard for VXI ensured that the hardware would be interoperable but such standards did not apply to the software Therefore the ideal new driver architecture should be a standard adopted by as many of the major vendors as possible to ensure that any code written for your instrument is portable across vendors as well as operating systems Finally most instruments export a set of commands to which they will respond Because the instrument needs to be flex
80. el instr will have a timeout of 5 s The fact that you are dealing with an OO based driver is somewhat irrelevant at this point As you become more experienced with VISA you will see more of the benefits of this approach But for now you can see that you can set the timeout with an operation function in a manner similar to that used with other drivers In addition the operation you need to remember viSetAttribute is the same operation you use to set any feature of any resource Now you send the string to the device status viWrite instr IDN n 6 amp retCount Again this is a familiar approach to programming You use a write operation to send a string to a device For now it is sufficient for you to understand that you can use a single operation viWrite to senda message to a device regardless of the interface to which it is connected Continuing you read back the string with a read operation status viRead instr buffer 200 amp retCount See Chapter 5 Message Based Communication for more information Communication Channels NI VISA User Manual The examples from Chapter 2 Introductory Programming Examples used an operation called viOpen to open communication channels with the instruments In VISA terminology this channel is known as a session A session connects you to the resource you addressed in the viOpen operation and keeps your communication and attribute settings unique fro
81. em and sets the compatibility mode accordingly If you change the preferences the new preferences take effect for any subsequent session you open National Instruments Corporation 3 5 NI VISA User Manual Chapter 3 VISA Overview When a session to a resource is opened interactively a window similar to the following appears This window uses the LabVIEW compatibility mode XI0 2 INSTR Session 0x00444B88 _ olx Enable Event Disable Event Discard Events Wait on Event Property Node Read Property Node Write Lock Unlock Attribute Name Current Value User Data x xI Return Value xO Fir Query the value of the specified attribute Execute Three main tabs appear in the window The initial tab is the Template tab which contains all of the operations dealing with events properties and locks Notice that there is a separate tab for each of these operations under the main tab The other main tabs are Basic I O and Register I O The Basic I O tab contains the operations for message based instruments while the Register I O tab contains the operations for register based instruments The Register I O tab does not appear for either GPIB or Serial instruments NI VISA User Manual 3 6 National Instruments Corporation Chapter 3 VISA Overview Programming with VISA Chapter 2 Introductory Programming Examples introduced some examples of how to write code for the VISA driver However the chapter
82. en to match a range of characters Alast Matches any character not in the enclosed 1ist You can use a hyphen to match a range of characters Matches 0 or more occurrences of the preceding character or expression Matches 1 or more occurrences of the preceding character or expression NI VISA User Manual 4 6 National Instruments Corporation Chapter 4 Initializing Your VISA Application Special Characters and Operators Meaning exp exp Matches either the preceding or following expression The or operator matches the entire expression that precedes or follows it and not just the character that precedes or follows it For example VXI GPIB means VXI GPIB not VX I G PIB exp Grouping characters or expressions The priority or precedence of the operators in regular expressions is as follows e The grouping operator in a regular expression has the highest precedence e The and operators have the next highest precedence e The or operator has the lowest precedence Notice that in VISA the string GPIB INSTR applies to both GPIB and GPIB VXI instruments The following table lists some examples of valid regular expressions that you can use with viFindRsrc Regular Expression Sample Matches GPIB INSTR Matches GPIBO 2 INSTR GPIB1 1 1 INSTR and GPIB VX1I1 8 INSTR GPIB O 9 INSTR Matc
83. ered read operations viVScanf and viBufRead Flushing a write buffer immediately sends any queued data to the device Flushing a read buffer discards the data in the read buffer An empty read buffer guarantees that the next call to viScanf viBufRead ora related operation reads data directly from the device rather than from queued data residing in the read buffer The easiest way to flush the buffers is with an explicit call to viF lush This operation can actually flush the buffers in two ways The simpler way uses discard flags These flags tell the driver to discard the contents of the buffers without performing any I O to the device For example status viFlush instr VI_READ_BUF_DISCARD However the flush operation can also complete the current I O before flushing the buffer For a write buffer this simply means to send the rest of the buffer to the device However for a read buffer the process is more involved Because you could be in the middle of a read from the device that is the device still has information to send it is possible to have the driver check the buffer for an EOS or END bit EOI signal If such a value exists in the buffer the contents of the buffer are discarded However if the driver can find no such value it begins reading from the device until it detects the end of the communication and then discards the data This process keeps the program and device in synchronization with each other
84. es of their respective companies WARNING REGARDING MEDICAL AND CLINICAL USE OF NATIONAL INSTRUMENTS PRODUCTS National Instruments products are not designed with components and testing intended to ensure a level of reliability suitable for use in treatment and diagnosis of humans Applications of National Instruments products involving medical or clinical treatment can create a potential for accidental injury caused by product failure or by errors on the part of the user or application designer Any use or application of National Instruments products for or involving medical or clinical treatment must be performed by properly trained and qualified medical personnel and all traditional medical safeguards equipment and procedures that are appropriate in the particular situation to prevent serious injury or death should always continue to be used when National Instruments products are being used National Instruments products are NOT intended to be a substitute for any form of established process procedure or equipment used to monitor or safeguard human health and safety in medical or clinical treatment Contents About This Manual Organization of This Manual Conventions Used in This Manual How to Use This Document Setimes eneeier e eE E E TE ea xi Related Documentation PaE E E E E TETT xi Customer Communication esessssesssseeestersrtererteststssestrsterstentetestetnsreteseeresrerenrrereerse xii Chapter 1 Introduction How to Use
85. esgacneesechtasenesdabbane deeds ot eh sieves nepar Eeke TEESE eases 6 1 High Level Access Operations sarei ri esnea n renee ene A RSS S 6 2 High Level Block Operations esssesessesesesseeessreessrrererrssesrsserrrsreestenrerreterrsseetrseeeesrent 6 4 Low Level Access Operations isses oe eere a ai aE ee aE Eo a ass 6 5 Overview of Register Accesses from COmMputers sesseesserersereerressererserereee 6 5 Using VISA to Perform Low Level Register Accesses eeeseeesererereeeee 6 7 Operations versus Pointer Dereference 0 0 0 eee cece eeeceseeeeeeeeeeeeseneeneenseees 6 8 Manipulating the Powter eseccc ecscesessceese est esosesceescecdvsusvitestestlescuvstenscesdestesvessadvers 6 8 Example O l NS eed cee aed A eee ad 6 9 BBS EOTS s c5sceass n n e ee Sento Sau a Hhaeendetibeptunetinas A A eee ness 6 10 Comparison of High Level and Low Level Acces 00 0 0 ceeeescesseeceeeeeeeeneeeseteenneenaes 6 10 Speed osie esaa a r eE oe aae Oe See S devo aT N aT a Sy 6 10 Base of D E E eke inet ne Sh 6 10 Accessing Multiple Address Spaces ccecesesceseeesceeeeeeeeeeeeeseeeeseeeneesaeeaees 6 11 Shared Memory Operations 0 csccseeseceeceseeseceseeesceseeeeeeeeeeeeeaeeseecaecsaecaeesaeeaeeeensees 6 11 Shared Memory Sample Code eee ceesceceseeesceseeeeceseeeeecaeeeeecaeesaesseeeaees 6 12 Example 6 2 ssi Svein sendin ees anos eaten ane 6 12 Chapter 7 VISA Events TtrOGU Ct OF sack sess eeck aseeeted es See ee vee r ted taped ta
86. examples table 6 3 default value for optional string segments table 6 3 example 6 1 6 2 to 6 3 strings for describing resources table 6 2 to 6 3 Visual Basic example A 9 function of 3 6 to 3 7 purpose 6 1 searching for resources 6 4 to 6 6 NI VISA User Manual Index example 6 2 6 4 to 6 5 range of expressions passed to viFindRsrc table 6 6 Visual Basic example A 10 to A 11 starting session with Default Resource Manager 3 7 to 3 7 Visa Transition Library VTL specification 1 2 viScanf operation automatically flushing formatted I O buffers 4 9 formatted I O operations 4 7 manually flushing formatted I O buffers 4 9 viSetAttribute operation programming example 2 1 2 3 setting timeout attribute example 3 4 synchronous read write services example 4 3 trigger service example 4 5 viSetBuf operation automatically flushing formatted I O buffers 4 10 controlling serial I O buffers 4 11 resizing formatted I O buffers 4 10 Visual Basic examples accessing resources A 9 event handling A 4 A 12 to A 13 locking A 14 to A 15 locks A 5 message based communication A 2 A 6 register based communication A 3 A 7 searching for resources A 10 to A 11 shared memory operations A 8 viTerminate operation 4 3 4 4 viUninstallHandler operation 7 8 viUnlock operation exclusive locks 8 3 nested locks 8 3 programming example 2 4 2 11 2 12 sample code 8 5 NI VISA User Manual l 8 viUnmapAddress
87. f the sessions currently active Similarly viDisableEvent disables the hardware when the last enabled session disables itself for the event Queuing The queuing mechanism in VISA gives an application the flexibility to receive events only when it requests them An application uses the viWaitOnEvent operation to retrieve the event information However in addition to retrieving events from the queue you can also use viWaitOnEvent in your application to halt the current execution and wait for the event to arrive Both of these cases are discussed in this section The event queuing process requires that you first enable the session to sense the particular event type When enabled the session can automatically queue the event occurrences as they happen A session can later dequeue these events using the viWaitOnEvent operation You can set the timeout to VI_TMO_IMMEDIATE if you want your application to check if any event of the specified event type exists in the queue CF Note Each session has a queue for each of the possible events that can occur This means that each queue is per session and per event NI VISA User Manual 7 4 National Instruments Corporation Chapter 7 VISA Events An application can also use viWaitOnEvent to wait for events if none currently exists in the queue When you select a non zero timeout value something other than VI_TMO_IMMEDIATE the operation retrieve
88. he Basic I O Services and the Formatted I O Services from within the VISA Instrument Control Resource INSTR All sessions to a VISA Instrument Control Resource INSTR opened using viOpen have full message based communication capabilities Of course if the device is a register based VXI device the message based operations return an error code VI_LERROR_NSUP_OPER to indicate that this device does not support the operations although the session still provides access to them This chapter discusses the uses of the Basic I O Services and the Formatted I O Services provided by the INSTR Resource in a VISA application Basic 1 0 Services The VISA Instrument Control Resource lets a controller interact with the device that it is associated with by providing the controller with services to do the following e Send blocks of data to the device e Request blocks of data from the device e Send the device clear command to the device e Trigger the device e Find information about the status of the device National Instruments Corporation 5 1 NI VISA User Manual Chapter 5 Message Based Communication ic Note For serial instruments the I O protocol must be set to VI_ASRL_488 for the clear trigger and status services to be enabled The following sections describe the operations provided by the VISA Instrument Control Resource for the Basic I O Services Synchronous Read Write Services NI VISA User Manual status
89. he status byte indicates whether the device is currently requesting service An operating system element that consists of a flow of control within a process In some operating systems a single process can have multiple threads each of which can access the same data space within the process However each thread has its own stack and all threads can execute concurrently with one another either on multiple processors or by time sharing a single processor A name given to the grouping of software modules in this case VISA resources with any associated or required hardware to give the functionality of a traditional stand alone instrument Within VISA a virtual instrument is the logical grouping of any of the VISA resources Virtual Instrument Software Architecture This is the general name given to this product and its associated architecture The architecture consists of two main VISA components the VISA resource manager and the VISA resources This is the name given to the part of VISA that defines all of the device specific resource classes VISA Instrument Control resources encompass all defined device capabilities for direct low level instrument control This is the name given to the part of VISA that defines all of the register or memory specific resource classes The VISA MEMACC resources encompass all high and low level services for interface level accesses to all memory defined in the system NI VISA User Manual Glossar
90. hes GPIBO 2 INSTR and GPIB1 1 1 INSTR but not GPIB VXI1 8 INSTR GPIB 0 INSTR Matches GPIB1 1 1 INSTR but not GPIBO 2 INSTRor GPIB12 8 INSTR VXI INSTR Matches VX1I0 1 INSTR but not GPIB VX1I0 1 INSTR GPIB VX1I INSTR Matches GPIB VX1I0 1 INSTR but not VXI0 1 INSTR National Instruments Corporation 4 7 NI VISA User Manual Chapter 4 Initializing Your VISA Application Regular Expression Sample Matches VXI 0 9 INSTR Matches VXI0 1 INSTR and GPIB VX1I0O 1 INSTR ASRL 0 9 INSTR Matches ASRL1 INSTR but not VAXILOt 5 s INSTR ASRL1 INSTR Matches ASRL1 INSTR and ASRL11 INSTR but not ASRL2 INSTR GPIB VXI INSTR Matches GPIB1 5 INSTR and VX10 3 INSTR but not ASRL2 INSTR GPIBO VXIO 1 INSTR Matches GPIBO 1 INSTR and VALOts Ls sINSTR INSTR Matches all INSTR device resources VXI 0 9 2 MEMACC Matches VXIO MEMACC and GPIB VXI1 MEMACC VXI0 Matches VX1I0 1 INSTR VXI0 2 INSTR and VXIO MEMACC Matches all resources Notice that in VISA the regular expressions used for resource matching are not case sensitive For example calling viFindRsrc with VX1 INSTR would return the same resources as invoking it with vxi instr Attribute Based Resource Matching NI VISA User Manual VISA can also sear
91. hs That is you can only modify the queue length before the first invocation of the viEnableEvent operation as shown in the following code segment status viSetAttribute instr VI_ATTR_MAX_QUEUE_LENGTH 10 status viEnableEvent instr VI_EVENT_SERVICE_REQ VI_QUEUE VI_NULL See Example 2 3 in Chapter 2 Introductory Programming Examples for an example of handling events via the queue mechanism National Instruments Corporation 7 5 NI VISA User Manual Chapter 7 VISA Events Callbacks Callback Modes NI VISA User Manual The VISA event model also allows applications to install functions that can be called back when a particular event type is received You need to install a handler before enabling a session to sense events through the callback mechanism Refer to the section The userHandle Parameter later in this chapter for more information The procedure works as follows 1 Use the viInstallHandler operation to install handlers to receive events 2 Use the viEnableEvent operation to enable the session for the callback mechanism as described earlier in the Enabling and Disabling Events section 3 The driver invokes the handler on every occurrence of the specified event 4 VISA provides the event context in the context parameter of viEventHandler The event context is like a data structure and contains information a
92. ializing VISA exiting return 1 Open communication with VXI Device at Logical Address 0 xf NOTE For simplicity we will not show error checking xy status viOpen defaultRM VXI0 0 INSTR VI_NULL VI_NULL amp self Allocate a portion of the device s memory status viMemAlloc self 0x100 amp offset Determine where the shared memory resides status viGetAttribute self VI_ATTR_MEM SPACE amp addrSpace NI VISA User Manual 6 12 National Instruments Corporation Chapter 6 Register Based Communication PA status viMapAddress self addrSpace offset 0x100 VI_FALS VI_NULL amp address viPeek16 self address amp value Access a different register by manipulating the pointer viPeek16 self ADD _OFFSET address 2 amp value status viUnmapAddress self status viMemFree self offset Close down the system status viClose self status viClose defaultRM return 0 National Instruments Corporation 6 13 NI VISA User Manual VISA Events This chapter describes the VISA event model and how to use it The following sections discuss the various events VISA supports and the event handling paradigm Introduction VISA defines a common mechanism to notify an application when certain conditions occur These conditions or occurrences are referred to as events An event is a means of communication between a VISA resou
93. ible these commands are often primitive functions of the device and require several commands to group them together so that the device can perform common tasks As a result programmers are faced with a lot of overhead Rather than making a simple request to get the data one must issue a series of commands to do task A do task B and so on prior to making the actual request to get the data 3 2 National Instruments Corporation Chapter 3 VISA Overview National Instruments began to ease this burden with the development of instrument drivers which encapsulate these primitive commands inside functions to perform the common tasks so users get up and running much faster The major drawback has been that it is difficult to keep up with the number of new devices that appear in the marketplace So another objective for this ideal driver would be for it to be an accepted standard for creating instrument drivers Then the vendors of the instruments could create the instrument drivers themselves and be assured that they can cover most of the systems on the market The VXIplug amp play Systems Alliance formed to create this software architecture The name of the driver is VISA for Virtual Instrument Software Architecture With VISA you can benefit from the interface independence features and the newly defined standard for instrument drivers Future versions of VISA will support more advanced features such as finer control of instruments and dist
94. ice that you cannot subtract any value from the address variable because the mapping starts at that location and cannot go backwards Example 6 1 shows how you can access other registers from address i Note The examples in this chapter show C source code You can find the same examples in Visual Basic syntax in Appendix A Visual Basic Examples NI VISA User Manual 6 8 National Instruments Corporation Chapter 6 Register Based Communication Example 6 1 include visa h define ADD _OFFSET addr offs ViPByte addr offs int main void ViStatus status For checking errors ViSession defaultRM instr Communication channels ViAddr address User pointer ViUInt16 value To store register valu Ky Begin by initializing the system EJ status viOpenDefaultRM amp defaultRM if status lt VI_SUCCESS Error Initializing VISA exiting return I Open communication with VXI Device at Logical Address 16 EJ NOTE For simplicity we will not show error checking y status viOpen defaultRM VX1I0 16 INSTR VI_NULL VI_NULL amp instr status viMapAddress instr VI_A16_SPACE 0 0x40 VI_FALSE VI_NULL amp address viPeekl6 instr address amp value Access a different register by manipulating the pointer Af viPeek16 instr ADD_OFFSET address 2 amp value status viUnmapAddress instr Close down the system status
95. ironment Framework Windows 3 x LabWindows CVI ANSI C WIN Visual Basic LabVIEW GWIN Windows 95 LabWindows CVI ANSI C WIN95 Visual Basic LabVIEW GWIN95 Windows NT LabWindows CVI ANSI C WINNT Visual Basic LabVIEW GWINNT Solaris 1 x LabWindows CVI ANSI C SUN Solaris 2 x LabVIEW GSUN HP UX 9 ANSI C LabWindows CVI HPUX HP UX 10 LabVIEW GHPUX Mac 68K ANSI C aio Mac PPC LabVIEW mr VxWorks ANSI C RF Although the LabWindows CVI development environment is not available on HP UX the run time libraries are Therefore a LabWindows CVI application developed on another framework can be ported to HP UX without modification This framework is not defined by the VXIplug amp play Systems Alliance but is still supported by NI VISA National Instruments Corporation 1 3 NI VISA User Manual Chapter 1 Introduction You may find that programming with NI VISA is not significantly different from programming with the I O software products that are currently available However the programming concepts model and paradigm that NI VISA uses create a solid foundation for taking advantage of VISA s more powerful features in the future NI VISA User Manual 1 4 National Instruments Corporation Introductory Programming Examples This chapter introduces some examples of common communication with instruments To help you become comfortable with VISA the examples avoid VISA terminology Chapter 3 VISA Overview looks
96. isters on a device at any other logical address The range of address locations you can access with Memory I O Services on a session is the range of address locations assigned to that device This is true for both High Level and Low Level Access operations To facilitate access to the device registers for multiple devices VISA allows you to open a MEMACC memory access session A session to a MEMACC Resource allows an application to access the entire memory range for a specified address space The MEMACC Resource supports the National Instruments Corporation 6 1 NI VISA User Manual Chapter 6 C7 Note C Note Register Based Communication same high level and low level operations as the INSTR Resource The only difference is that all register addresses are absolute addresses in VXIbus address space A session to a MEMACC Resource supports only the high level low level and resource template operations A MEMACC session does not support the other INSTR operations In VISA you can choose between two styles for accessing registers High Level Access or Low Level Access Both styles have operations to read the value of a device register and write to a device register as shown in the following table In addition there are high level operations designed to read or write a block of data The block move operations do not have a low level counterpart High Level High Level Low Level Access Block Access
97. ling viClose on the event context is therefore both unnecessary and incorrect Event Context with the Callback Mechanism In the case of callbacks the event is passed to you in a function so the driver has a chance to destroy it when the function ends This has two important repercussions First you do not need to call viclose on the event inside the callback function Indeed calling this operation on the event could lead to serious problems because VISA will access the event to close it when your callback returns Secondly the event itself has a life only as long as the callback function is executing Therefore if you want to keep any information about the event after the callback function you should use viGetAttribute to retrieve the information for storage Any references to the event itself becomes invalid when the callback function ends National Instruments Corporation 7 11 NI VISA User Manual Chapter 7 VISA Events Exception Handling By using the VISA event VI_EVENT_EXCEPTION you can have one point in your code that traps all errors and handles them appropriately This means that after you install and enable your VISA exception handler you do not have to check the return status from each operation which makes the code easier to read and maintain How an application handles error codes is specific to both the device and the application For one application an error could mean different things from differe
98. lities of a device In general this term is synonymous with the connotation of the word object in object oriented architectures For VISA resource more specifically refers to a particular implementation or instance in object oriented terms of a Resource Class second The same as communication channel A communication path between a software element and a resource Every communication channel in VISA is unique Same as DLL A file containing a collection of functions that can be used by multiple applications This term is usually used for libraries on UNIX platforms A block of memory that is accessible to both a client and a server The memory block operates as a buffer for communication This is unique to register based interfaces such as VXI G 4 National Instruments Corporation SRQ status byte thread V virtual instrument VISA VISA instrument control resources VISA memory access resources National Instruments Corporation G 5 Glossary IEEE 488 Service Request This is an asynchronous request from a remote device that requires service A service request is essentially an interrupt from a remote device For GPIB this amounts to asserting the SRQ line on the GPIB For VXI this amounts to sending the Request for Service True event REQT A byte of information returned from a remote device that shows the current state and status of the device If the device follows IEEE 488 conventions bit 6 of t
99. lock with a requested name status viLock instr VI_SHARED_LOCK 15000 MyLockName accessKey This example attempts to acquire a shared lock with MyLockName as the requestedKey and a timeout of 15 s If the call is successful accessKey will contain MyLockName If you want to have VISA generate a key simply pass VI_NULL in place of MyLockName and VISA will return a unique key in accessKey that other sessions can use for locking the resource 8 2 National Instruments Corporation Chapter 8 VISA Locks Acquiring an Exclusive Lock While Owning a Shared Lock When multiple sessions have acquired a shared lock VISA allows one of the sessions to acquire an exclusive lock as well as the shared lock it is holding That is a session holding a shared lock can also acquire an exclusive lock using the viLock operation The session holding both the exclusive and shared lock has the same access privileges it had when it was holding only the shared lock However the exclusive lock precludes other sessions holding the shared lock from accessing the locked resource When the session holding the exclusive lock unlocks the resource using the viUnlock operation all the sessions including the one that acquired the exclusive lock again have all the access privileges associated with the shared lock This circumstance is useful when you need to synchronize multiple sessions holding a shared lock A session holding an exclusive and shar
100. lock with certain sessions and exclude access from other sessions This section discusses the mechanism that makes it possible to share locks VISA defines a lock type VI_SHARED_LOCK that gives exclusive access privileges to a session along with the capability to share these exclusive privileges at the discretion of the original session When locking sessions with a shared lock the locking session gains an access key The session can then share this lock with any other session by passing the access key VISA allows user applications to specify an access key to be used for lock sharing or VISA can generate the access key for an application If the application chooses to specify the accessKey other sessions that want access to the resource must choose the same unique accessKey for locking the resource Otherwise when VISA generates the accessKey the session that gained the shared lock should make the accessKey available to other sessions for sharing access to the locked resource Before the other sessions can access the locked resource they must acquire the lock using the same access key in the accessKey parameter of the viLock operation Invoking viLock with the same access key will register the new session with the same access privileges as the original session All sessions that share a resource should synchronize their accesses to maintain a consistent state of the resource The following code is an example of obtaining a shared
101. locking error depending on the operation and the type of lock used VISA defines two different types or modes of locks exclusive and shared locks which are denoted by VI_EXCLUSIVE_LOCK and VI_SHARED_LOCK respectively viLock is used to acquire a lock on a resource and viUnlock is used to release the lock If a session has an exclusive lock other sessions cannot modify global attributes or invoke operations but can still get attributes and set local attributes If the session has a shared lock other sessions that have shared locks can also modify global attributes and invoke operations Regardless of which type of lock a session has if the session is closed without first being unlocked VISA automatically performs a viUnlock on that session National Instruments Corporation 8 1 NI VISA User Manual Chapter 8 VISA Locks Lock Sharing NI VISA User Manual Because the locking mechanism in VISA is session based multiple threads sharing a session that has locked a VISA resource have the same privileges for accessing the resource However some applications might have separate sessions to aresource for these multiple threads and might require that all the sessions in the application have the same privileges as the session that locked the resource In other cases there might be a need to share locks among sessions in different applications Essentially sessions that have a lock to a resource may share the
102. m Specific and Portability Issues This chapter discusses programming information for you to consider when developing applications that use the NI VISA driver After installing the driver software you can begin to develop your VISA application software Remember that the NI VISA driver relies on NI 488 2 and NI VXI for driver level I O accesses Windows 95 NT users On VXI and MXI systems use T amp M Explorer to run the VXI Resource Manager configure your hardware and assign VME and GPIB VXI addresses For GPIB systems use the system Device Manager to configure your hardware To control instruments through serial ports you can use T amp M Explorer to change the default settings or you can perform all the necessary configuration at run time by setting VISA attributes All other platforms On VXI and MXI systems you must still run vxiinit and resman and use vxiedit or vxitedit for configuration purposes Similarly for GPIB and GPIB VXI systems you still use the GPIB Control Panel applet or ibconf to configure your system To control instruments through serial ports you can do all necessary configuration at run time by setting VISA attributes The NI VISA Programmer Reference Manual contains detailed descriptions of the VISA attributes events and operations Windows Solaris and HP UX users can access this same information online through NI visa hlp which you can find in the NIvisa directory National Instruments Corpor
103. m other sessions to the same resource In VISA a resource can have 3 8 National Instruments Corporation Chapter 3 VISA Overview multiple sessions to it from the same program and even from other programs simultaneously Therefore you must consider some things about the resource to be local that is unique to the session and other things to be global that is common for all sessions to the resource If you look at the descriptions of the various attributes supported by the VISA resources you will see that some are marked global such as VI_ATTR_INTF_TYPE and others are marked local such as VI_ATTR_TMO_VALUE For example the interface bus that the resource is using to communicate with the device VI_LATTR_INTF_TYPE is the same for everyone talking to the resource and is therefore a global attribute However different programs may have different timeout requirements and so the timeout value VI_ATTR_TMO_VALUE for communication is a local attribute Again look at Example 2 1 To open communication with the instrument that is to create a session to the INSTR Resource you use the viOpen operation as shown below status viOpen defaultRM GPIBO 1 INSTR VI_NULL VI_NULL amp instr In this case the interface to which the instrument is connected is important but only as a means to uniquely identify the instrument The code above references a GPIB device on bus number 0 with primary address 1 The
104. n remotely control VXI devices when using a GPIB VXI controller Multiple GPIB VXI Support Windows 95 NT users can refer to the T amp M Explorer utility to add multiple National Instruments GPIB VXI controllers or any other vendor s GPIB V XI controller to your system WIN16 and UNIX users must use the VISAconf utility to add the controllers Serial Port Support The maximum number of serial ports that NI VISA currently supports on any platform is 32 The default numbering of serial ports is system dependent as shown in Table 9 2 National Instruments Corporation 9 5 NI VISA User Manual Chapter 9 NI VISA Platform Specific and Portability Issues VME Support NI VISA User Manual Table 9 2 How Serial Ports Are Numbered Platform Method Windows 3 x ASRL1 ASRL4 access COM1 COM4 Windows 95 ASRL10 ASRL13 access LPT1 LPT4 Windows NT Macintosh 68K ASRL1 accesses the modem port Macintosh PPC ASRL2 accesses the printer port Solaris 2 x ASRL1 ASRL6 access dev cua a dev cua f Solaris 1 x ASRL1 ASRL6 access dev ttya dev ttyf HP UX 9 ASRL1 and ASRL2 access serial ports 1 and 2 HP UX 10 through dev tty00 and dev tty01 respectively Additional ports are numbered consecutively starting at ASRL3 which uses dev tty02 VxWorks NI VISA for VxWorks does not currently support the serial interface To access VME devices in your system you must configure NI
105. n Chapter 9 NJ VISA Platform Specific and Portability Issues to verify you are establishing connection to the correct port Refer to the online help or to the N VISA Programmer Reference Manual for a complete range of values for the attributes Some other useful ASRL attributes are as follows 7 VILA R_ASRL_END_IN defines the method of terminating reads Defau Its to VI_ASRL_END_TERMCHAR This means that the read operation will stop whenever the character specified by VILA R ERMCHAR is encountered regardless of the state of VILA R VI_A ERMCHAR_EN R_ASRL_END_OUT defines the method of terminating writes Defau lts to VI_ASRL_END_NONE This means that the setting of VI_A NI VISA User Manual R_ S END_EN is irrelevant 4 12 National Instruments Corporation Message Based Communication This chapter shows how to use the VISA library in message based communication Introduction Whether you are using RS 232 GPIB or VXI message based communication is a standard protocol for controlling and receiving data from instruments Because most message based devices have similar capabilities it is natural that the driver interface should be consistent Under VISA controlling message based devices is the same regardless of whether those devices are serial GPIB or VXI instruments VISA message based communication includes t
106. n to launch the NI VXI interactive utility or the NI 488 interactive utility This gives you convenient links into the interactive utilities for the drivers VISA calls in case you would like to try debugging at this level Double clicking on any of the instrument descriptors shown in the VISAIC window opens a session to that instrument Opening a session to the instrument produces a window with a series of tabs for interactively running VISA commands The exact appearance of these tabs depends on which compatibility mode VISAIC is in To access the compatibility mode and other VISAIC preferences select Edit Preferences to bring up the following window 3 4 National Instruments Corporation Chapter 3 VISA Overview Preferences x Preferences will be applied to new session windows Class Tab Color Compatibility Mode _ i LabWindows CVI Operation Tab Color LabVIEW Default Resource View Selected Tab Text Color By Connection By Type VY Show VISA session number in window title F Show duplicate GPIB and GPIB VXI resources V Show Memory Access resources F Load configured settings when available Cancel Default The VISA implementations are slightly different in LabVIEW and LabWindows CVI These differences are reflected in the operation tabs that are shown when you open a session to a resource Windows 95 NT users VISAIC detects whether you have LabVIEW and or LabWindows CVI installed on your syst
107. ned on a per device basis However the VXI hardware triggers by definition have interface level triggering In other words you cannot prevent two devices from receiving a SYNC pulse of TTL3 if both devices are listening to the line Therefore if you need to trigger multiple devices off a single VXI trigger line you can do this by sending the trigger to any one of the devices on the line National Instruments Corporation 5 5 NI VISA User Manual Chapter 5 Message Based Communication Status Service Request Service It is fairly common for a device to need to communicate with a controller at a time when the controller is not planning to talk with the device For example if the device detects a failure or has completed a data acquisition sequence it may need to get the attention of the controller In both GPIB and VXI this is accomplished through a Service Request SRQ Although the actual technique for delivering this service request to the controller differs between the two interfaces the end result is that an event VI_EVENT_SERVICE_REQ is received by the VISA driver You can find more details on event notification and handling in Chapter 2 Introductory Programming Examples and Chapter 7 VISA Events At this time just assume that the program has received the event and has a handle to the data through the eventContext parameter Under VISA the VI_EVENT_SERVICE_REQ event contains no additional information
108. not ask for more windows than are available The HLA operations avoid this problem by restoring the window to the previous setting when they are done Even if all windows are currently in use by LLA operations you can still use HLA functions because they will save the state of the window remap access and then restore the window As a result you can have an unlimited number of HLA windows Shared Memory Operations Note There are two distinct cases for using shared memory operations In the first case the local controller exports general purpose memory to the A24 A32 space In the second case remote devices export memory into A24 A32 space Unlike the first case the memory exported to A24 A32 space may not be general purpose so the VISA Shared Memory services do not control memory on remote devices A common configuration in a VXI system is to export memory to either the A24 or A32 space The local controller usually can export such memory This memory can then be used to buffer the data going to or from the instruments in the system However a common problem is preventing multiple devices from using the same memory In other words a memory manager is needed on this memory to prevent corruption of the data The VISA Shared Memory operations viMemAlloc and viMemF ree provide the memory management for a specific device namely the local controller Since these operations are part of the INSTR resource they are associated wi
109. ns such as format syntax parameters and possible errors Windows 95 NT users The NI VISA Programmer Reference Manual is not included in Windows 95 NT kits Windows 95 NT users can access this information through the NI visa h1lp file at Start Programs VXIpnp VISA Help Related Documentation The following documents contain information that you may find helpful as you read this manual e ANSI TEEE Standard 488 1 1987 IEEE Standard Digital Interface for Programmable Instrumentation e ANSI IEFE Standard 488 2 1992 IEEE Standard Codes Formats Protocols and Common Commands e ANSI TEEE Standard 1014 1987 IEEE Standard for a Versatile Backplane Bus VMEbus e ANSI TEEE Standard 1155 1992 VMEbus Extensions for Instrumentation VXIbus e ANSI ISO Standard 9899 1990 Programming Language C e NI 488 2 Function Reference Manual for DOS Windows National Instruments Corporation e NI 488 2 User Manual for Windows National Instruments Corporation e NI VXI Programmer Reference Manual National Instruments Corporation e NI VXI User Manual National Instruments Corporation National Instruments Corporation xi NI VISA User Manual About This Manual e VPP 1 Charter Document e VPP 2 System Frameworks Specification e VPP 3 1 Instrument Drivers Architecture and Design Specification e VPP 3 2 Instrument Driver Functional Body Specification e VPP 3 3 Instrument Driver Interactive Developer Interface Spe
110. nt and use only a single operation to send the string Consider the following code segment Retrieve user s selections Assume the variable X holds the choice from the following menu 1 VDC 2 Ohms 3 Amps status viPrintf instr F d X Here the variable x corresponds to the type of measurement denoted by a number matching the function number for the instrument Without formatted I O the result would have been either sprintf buffer F d X viWrite instr buffer strlen buffer amp retCount or National Instruments Corporation 5 7 NI VISA User Manual Chapter 5 Message Based Communication switch X case 1 viWrite instr F1 2 amp retCount break case 2 viWrite instr F2 2 amp retCount break In addition there is an operation viQueryf that combines the functionality of a viPrintf followed by a viScanf operation viQueryf is used to query the device for information status viQueryf instr IDN n s buf 1 0 Buffer Operations Another method for communicating with your instruments using formatted T O functions is using the formatted I O buffer functions visPrintf viSScanf viBufRead and viBufWrite You can use these functions to manipulate a buffer that you will send or receive from an instrument For example you may want to bring information from a device into a buffer and then manipulate it yourself To do this first call
111. nt devices and might even be ignored under certain circumstances for another any error could always be fatal For an application that needs to treat all errors as fatal one possible use for this event type would be to print out a debug message and then exit the application Because the method of installing the handler and then enabling the event has already been covered the following code segment shows only the handler itself ViStatus _VI_FUNCH myEventHandler ViSession vi ViEventType etype ViEvent event ViAddr uHandle ViChar rsrcName 256 operName 256 ViStatus stat ViSession rm if etype VI_EVENT_EXCEPTION viGetAttribute vi VI_ATTR_RSRC_NAME rsrcName viGetAttribute event VI_ATTR_OPER_NAME operName viGetAttribute event VI_LATTR_STATUS amp stat printf Session 0x 081X to resource s caused error 0x 081X in operation s n vi rsrcName stat operName Use this code only if you will not return control to VISA viGetAttribute vi VI_ATTR_RM_SESSION amp rm viClose event viClose vi viClose rm exit 1 exit the application immediately code for other event types return VI_SUCCESS NI VISA User Manual 7 12 National Instruments Corporation Chapter 7 VISA Events If you wanted just to print out a message you would leave out the code that closes the obj
112. nt from the other examples in this chapter Example 2 2 include visa h int main void ViStatus status For checking errors EJ ViSession defaultRM instr Communication channels Ef ViUInt16 deviceID To store the value Begin by initializing the system aes status viOpenDefaultRM amp defaultRM if status lt VI_SUCCESS Error Initializing VISA exiting return 1 Open communication with VXI Device at Logical Addr 16 xf NOTE For simplicity we will not show error checking ey status viOpen defaultRM VXI0 16 INSTR VI_NULL VI_NULL amp instr Read the Device ID and write to memory in A24 space status viInl6 instr VI_A16_SPACE 0 amp deviceID status viOut16 instr VI_A24 SPACE 0 0x1234 Close down the system status viClose instr status viClose defaultRM return 0 National Instruments Corporation 2 5 NI VISA User Manual Chapter 2 Introductory Programming Examples Example 2 2 Discussion NI VISA User Manual The general structure of this example is very similar to that of Example 2 1 For this reason we merely point out the basic differences as denoted in bold text e A different address string is used for the VXI device e The string functions from Example 2 1 are replaced with register functions The address string is still the same format as the address string in Example 2 1 but it has replaced the GP
113. nual You can skip over this section if you are exclusively using GPIB or serial communication Register based programming applies only to VXI GPIB VXI VISA has two standard methods for accessing registers The first method uses High Level Access functions You can use these functions to specify the address to access the functions then take care of the necessary details to perform the access from mapping an I O window to checking for failures The drawback to using these functions is the amount of software overhead associated with them To reduce the overhead VISA also has Low Level Access functions These functions break down the tasks done by the High Level Access functions and let the program perform each task itself The advantage is that you can optimize the sequence of calls based on the style of register I O you are about to perform However you must be more knowledgeable about how register accesses work In addition you cannot check for errors easily The following example shows how to perform register I O using the High Level 2 4 National Instruments Corporation Chapter 2 Introductory Programming Examples Access functions which is the method we recommend for new users If you are an experienced user or understand register I O concepts you can use the Low Level Access Operations section in Chapter 6 Register Based Communication CF Note Examples 2 2 through 2 4 use bold text to distinguish lines of code that are differe
114. nual viii National Instruments Corporation About This Manual Organization of This Manual The NI VISA User Manual is organized as follows National Instruments Corporation Chapter 1 Introduction discusses how to use this manual lists what you need to get started and contains a brief description of the VISA Library Chapter 2 Introductory Programming Examples introduces some examples of common communication with instruments Chapter 3 VISA Overview contains an overview of the VISA Library Chapter 4 Initializing Your VISA Application describes the steps required to prepare your application for communication with your device Chapter 5 Message Based Communication shows how to use the VISA library in message based communication Chapter 6 Register Based Communication shows how to use the VISA library in register based communication Chapter 7 VISA Events describes the VISA event model and how to use it Chapter 8 VISA Locks describes how to use locks in VISA Chapter 9 NI VISA Platform Specific and Portability Issues discusses programming information for you to consider when developing applications that use the NI VISA driver Appendix A Visual Basic Examples shows the Visual Basic syntax of the ANSI C examples given earlier in this manual The examples use the same numbering sequence for easy reference Appendix B Customer Communication contains forms you can use to request help from Nati
115. o a specified section of an address space and makes the specified range of addresses accessible to the requester This function is independent of memory allocation An action defined by a resource that can be performed on a resource In general this term is synonymous with the connotation of the word method in object oriented architectures NI VISA User Manual Glossary P process R register resource class resource or resource instance session shared library or shared object shared memory NI VISA User Manual An operating system element that shares a system s resources A multi process system is a computer system that allows multiple programs to execute simultaneously each in a separate process environment A single process system is a computer system that allows only a single program to execute at a given point in time An address location that can be read from or written into or both It may contain a value that is a function of the state of hardware or can be written into to cause hardware to perform a particular action In other words an address location that controls and or monitors hardware The definition for how to create a particular resource In general this is synonymous with the connotation of the word class in object oriented architectures For VISA Instrument Control resource classes this refers to the definition for how to create a resource which controls a particular capability or set of capabi
116. o have the following information about the register e The address space where the register is located In a VXI interface bus for example the address space can be A16 A24 or A32 e The offset of the register relative to the device for the specified address space You do not need to know the actual base address of the device just the offset Note When using the MEMACC Resource you need to provide the absolute VXI address base offset for the register The following sample code reads the Device Type register of a VXI device located at offset 0 from the base address in A16 space and writes a value to the A24 shared memory space at offset 0x20 this offset has no special significance status vilInl6 instr VI_A16_SPACE 0 amp retValue status viOut16 instr VI_A24_ SPACE 0x20 0x1234 With this information the HLA operations perform the necessary hardware setup perform the actual register I O check for error conditions and restore the hardware state To learn how to perform these steps individually see the Low Level Access operations The HLA operations can detect and handle a wide range of possible errors HLA operations perform boundary checks and return an error code VI_ERROR_INV_OFFSET to disallow accesses outside the valid range of addresses that the device supports The HLA operations also trap and handle any bus errors appropriately and then report the bus error as VI_ERROR_BERR
117. om the device on a specific session e VI_EVENT_VXI_SIGP VXI Signal Processor is a notification of a VXIbus signal or VXIbus interrupt from the device Notice that VISA supports the VI_EVENT_VXI_SIGP event only for VXI interfaces so you can enable sessions only to VXI devices for this event e VI_EVENT_VXI_VME_INTR VXI VME Interrupt is a notification of a VXIbus interrupt from the device Notice that VISA supports the VI_EVENT_VXI_VME_INTR event only for VXI or VME interfaces so you can enable sessions only to VXI or VME devices for this event e VI_EVENT_TRIG VXI Trigger is a notification of a VXIbus trigger VXIbus interfaces support this event Therefore you can enable sessions only to VXI devices for this event VISA defines following two events for both the Instrument Control Resource and the Memory Access Resource e VI_EVENT_IO_COMPLETION I O Completion is a notification that an asynchronous I O operation has completed The I O Completion event applies to all asynchronous operations which currently includes viReadAsync viWriteAsync and viMoveAsync You can use all three operations with the INSTR Resource but only viMoveAsync with the MEMACC Resource e VI_EVENT_EXCEPTION Exception is a notification that an error condition has occurred during an operation invocation The exception event
118. onal 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 ndex contains an alphabetical list of key terms and topics in this manual including the page where you can find each one ix NI VISA User Manual About This Manual Conventions Used in This Manual er bold bold italic italic monospace monospace bold monospace italic paths NI VISA User Manual The following conventions are used in this manual The symbol leads you through nested menu items and dialog box options to a final action For example 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 options from the last dialog box The symbol indicates that the text following it applies only to a specific product or a specific operating system This icon to the left of bold italicized text denotes a note which alerts you to important information Bold text denotes the names of menus menu items parameters dialog boxes dialog box buttons or options icons windows or Windows 95 tabs Bold italic text denotes a note caution or warning Italic text denotes variables emphasis a cross reference or an introduction to a key concept This fon
119. order of portability 1 Any VISA defined operation 2 The LabWindows CVI ProcessSystemEvents function 3 The Windows PeekMessage or Yield functions For example the following code in a LabWindows CVI application does allow callbacks to occur correctly while intr_recv ProcessSystemEvents give up time 9 4 National Instruments Corporation Chapter 9 NI VISA Platform Specific and Portability Issues Notice that NI VISA on Windows 95 Windows NT and all UNIX platforms does not require you to call VISA operations or give up processor time to receive callbacks However because occasionally calling VISA operations ensures that callbacks will be invoked correctly on any platform you should keep these issues in mind when writing code that you want to be portable Multiple Interface Support Issues This section contains information about how to use or configure your NI VISA software for certain types of interfaces VXI and GPIB Platforms NI VISA supports all existing National Instruments VXI GPIB and serial hardware for the operating systems on which NI VISA exists For VXI this includes MXI 1 and MXI 2 platforms the GPIB VXI and the line of VXIpc embedded computers For GPIB this includes but is not limited to the PCI GPIB NB GPIB GPIB SPARC series the full line of AT GPIB TNT boards and the GPIB ENET box which you can use to remotely control GPIB devices With the GPIB ENET you can eve
120. ore information Example 2 4 uses the simpler form the exclusive lock to prevent other VISA applications from modifying the state of the specified serial port ViStatus status For checking errors Xf ViSession defaultRM instr Communication channels ViUInt32 retCount Return count from string I 0 ViChar buffer MAX_CNT Buffer for string I O Begin by initializing the system K status viOpenDefaultRM amp defaultRM if status lt VI_SUCCESS Error Initializing VISA exiting E return 1 Open communication with Serial Port 1 NOTE For simplicity we will not show error checking K status viOpen defaultRM ASRL1 INSTR VI_NULL VI_NULL amp instr NI VISA User Manual 2 10 National Instruments Corporation Chapter 2 Introductory Programming Examples Set the timeout for message based communication Sf status viSetAttribute instr VI_ATTR_TMO_VALUE 5000 Lock the serial port so that nothing else can use it status viLock instr VI_EXCLUSIVE_LOCK 5000 VI_NULL VI_NULL Set serial port settings as needed Defaults 9600 Baud no parity 8 data bits 1 stop bit status viSetAttribute instr VI_ATTR_ASRL_BAUD 2400 status viSetAttribute instr VI_ATTR_ASRL_DATA BITS 7 Ask the device for identification status viWrite instr IDN n 6 amp retCount status viRead instr buffer MAX_CNT amp retCount Unlock
121. ort support 9 5 service request service See status service request service sessions See also communication channels definition 3 5 shared locks 8 1 See also locks NI VISA User Manual Index shared memory operations 5 11 to 5 13 examples sample code example 5 2 5 12 to 5 13 Visual Basic example A 8 overview 5 11 to 5 12 when to use note 5 11 stack size under Windows 3 x 9 7 status service request service 4 6 to 4 7 synchronous read write services 4 2 to 4 3 T technical support B 1 to B 2 telephone and fax support B 2 termination mechanisms setting attributes for 4 2 to 4 3 timeout setting example 3 4 trigger services 4 5 to 4 6 description 4 5 to 4 6 device triggering 4 5 interface level 4 6 U userHandle parameter 7 7 to 7 8 V Variable List operations 4 8 viAssertTrigger operation 4 5 VI_ATTR_DEST_INCREMENT 5 4 VI_ATTR_MAX_QUEUE_ LENGTH 7 5 7 7 VI_ATTR_RD_BUF_OPER_MODE 4 10 VI_ATTR_SEND_END_EN 4 3 VI_ATTR_SRC_INCREMENT 5 4 VI_ATTR_TERMCHAR 4 3 VI_ATTR_TERMCHAR EN 4 3 VI_ATTR_TMO_VALUE 3 4 4 3 NI VISA User Manual l 6 VI_ATTR_TRIG_ID 4 5 VI_ATTR_WR_BUF_OPER_MODE 4 10 viClear operation 4 4 4 10 viClose operation closing communication channels example 3 6 closing resource manager session 6 4 event context 7 11 viDisableEvent operation disabling events 7 3 to 7 4 7 5 programming example 2 3 2 9 viDiscardEvents operation 7 5 7 6
122. r Set the timeout for message based communication af status viSetAttribute instr VI_ATTR_TMO_VALUE 5000 Ask the device for identification x status viWrite instr IDN n 6 amp retCount status viRead instr buffer MAX_CNT amp retCount Your code should process the data Close down the system status viClose instr status viClose defaultRM return 0 NI VISA User Manual 2 2 National Instruments Corporation Chapter 2 Introductory Programming Examples Example 2 1 Discussion We can break down Example 2 1 into the following steps 1 National Instruments Corporation Begin by initializing the VISA system For this task you use viOpenDefaultRM which opens a communication channel with VISA itself This channel has a purpose similar to a telephone line The function call is analogous to picking up the phone and dialing the operator From this point on the phone line connects you to the driver Any communication on the line is between you and the driver only Chapter 3 VISA Overview has more details about viOpenDefaultRM but for now it is sufficient for you to understand that the function initializes VISA and must be the first VISA function called in your program Now you must open a communication channel to the device itself using viOpen Notice that this function uses the handle returned by viOpenDefau1tRM to identify the VISA driver You then specify the add
123. r dereferences in C to access the VXIbus 6 6 National Instruments Corporation Chapter 6 Register Based Communication Using VISA to Perform Low Level Register Accesses The first LLA operation you need to call to access a device register is the viMapAddress operation which sets up the hardware window and obtains the appropriate pointer to access the VXI address space The viMapAddress operation first programs the hardware to map local CPU addresses to VXI addresses as described in the previous section In addition it returns a pointer that you can use to access the registers The following code is an example of programming the hardware to access A16 space status viMapAddress instr VI_A16_SPACE 0 0x40 VI_FALSE VI_NULL amp address This sample code sets up the hardware to map A16 space starting at offset 0 for 0x40 bytes and returns the pointer to the window in address Remember that the offset is relative to the base address of the device we are talking to through the instr session not from the base of A16 space itself Therefore offset 0 does not mean address 0 in A16 space but rather the starting point of the device s A16 memory You can ignore the VI_FALSE and VI_NULL parameters for the most part because they are reserved for definition by a future version of VISA Note To access the device registers through a MEMACC session you need to provide the absolute VXIbus addresses base address for device
124. r to define and implement standards for system level issues beyond the scope of the VXIbus specifications As a step toward industry wide software compatibility the alliance developed one specification for I O software the Virtual Instrument System Architecture or VISA The VISA specification defines a next generation I O software standard not only for VXI but also for GPIB and serial interfaces With the VISA standard endorsed by over 35 of the largest instrumentation companies in the industry including Tektronix Hewlett Packard and National Instruments VISA unifies the industry to make software interoperable reusable and able to stand the test of time Before VISA there were many different commercial implementations of I O software for VXI GPIB and serial interfaces however none of these T O software products were standardized or interoperable When the VISA standard was initially endorsed commercial VISA products were not yet available To quickly realize the benefits of VXIplug amp play the alliance developed the VISA Transition Library VTL specification The VTL reflected the alliance s strategy to deliver multivendor software interoperability while at the same time moving the entire industry towards a common robust VISA foundation for the future Software written to VTL such as instrument drivers and executable soft front panels will also run on present and future VISA implementations without modification All VXIpl
125. rce and its applications Typically events occur because of a condition requiring the attention of applications The VISA event model provides the following two different ways for an application to receive event notification e The first method uses a queuing mechanism You can use this method to place all of the occurrences of a specified event in a queue The queuing mechanism is generally useful for noncritical events that do not need immediate servicing The Queuing section in this chapter describes this mechanism in detail e The other method is to have VISA invoke a function that the program specifies prior to enabling the event This is known as a callback handler and is invoked on every occurrence of the specified event The callback mechanism is useful when your application requires an immediate response The Callbacks section in this chapter describes this mechanism in detail The queuing and callback mechanisms are suitable for different programming styles However because these mechanisms work independently of each other you can have them both enabled at the same time National Instruments Corporation 7 1 NI VISA User Manual Chapter 7 VISA Events Supported Events NI VISA User Manual The following four events are currently defined for the Instrument Control Resource These events do not apply to the Memory Access Resource e VI_EVENT_SERVICE_REQ Service Request is a notification of a service request fr
126. rd for a GPIB VXI controller Use the GPIB keyword to establish communication with a GPIB device Use the ASRL keyword to establish communication with an asynchronous serial such as RS 232 device Refer to Chapter 9 NI VISA Platform Specific and Portability Issues for help in determining exactly which resource you may be accessing In some cases such as serial ASRL resources the naming conventions with other serial naming conventions may be confusing In the Windows platform COM corresponds to ASRL1 unlike in LabVIEW where COM is accessible using port number 0 The default values for optional string segments are as follows Optional String Segment Default Value board 0 secondary address none The following table shows examples of address strings Address String Description VX1I0 1 INSTR A VXI device at logical address 1 in VXI interface VXIO GPIB VX1I 9 INSTR A VXI device at logical address 9 in a GPIB VXI controlled VXI system GPIB 1 0 INSTR A GPIB device at primary address and secondary address 0 in GPIB interface 0 ASRL1 INSTR A serial device attached to interface ASRL1 VXI MEMACC Board level register access to the VXI interface GPIB VXI1 MEMACC Board level register access to GPIB VXI interface number 1 National Instruments Corporation 4 3 NI VISA User Manual Chapter 4 Initializing Your VISA Application Finding Resources
127. re the driver is able to perform the address calculation itself The 0 indicates the first register in the 0x40 bytes of address space or the Device ID register The same holds true for the viout16 call Even in A24 or A32 space although it is possible that you are talking to a device whose memory starts at 0x0 it is more likely that the VXI Resource Manager has provided some other offset such as 0x200000 for the memory However because instr identifies the device and the Resource Manager has told 2 6 National Instruments Corporation Chapter 2 Introductory Programming Examples the driver the offset address of the device s memory you do not need to know the details of the absolute address Just provide the offset within the memory space and VISA does the rest Again when you are done with the register I O use viClose to shut down the system Example of Handling Events When dealing with instrument communication it is very common for the instrument to require service from the controller when the controller is not actually looking at the device an asynchronous event or simply an event Examples of this are the service request SRQ interrupts and signals In VISA you can handle these and other events through either callbacks or a software queue Callbacks Using callbacks you can have sections of code that are never explicitly called by the program but instead are called by the driver whenever an event occurs
128. remap Furthermore because HLA operations encapsulate many status checking capabilities not included in LLA operations HLA operations have higher software overhead For these reasons HLA is slower than LLA in many cases For block transfers the high level viMoveXX operations perform the fastest HLA operations are easier to use because they encapsulate many status checking capabilities not included in LLA operations which explains the higher software overhead and lower execution speed of HLA operations HLA operations also encapsulate the mapping and unmapping of hardware windows which means that you do not need to call viMapAddress and viUnmapAddress separately 6 10 National Instruments Corporation Chapter 6 Register Based Communication Accessing Multiple Address Spaces You can use LLA operations to access only the address space currently mapped To access a different address space you need to perform a remapping which involves calling viUnmapAddress and viMapAddress Therefore LLA programming becomes more complex without much of a performance increase for accessing several address spaces concurrently In these cases the HLA operations are superior In addition if you have several sessions to the same or different devices all performing register I O they must compete for the finite number of windows available When using LLA operations you must allocate the windows and always ensure that the program does
129. ress of the device you want to talk to Continuing with the phone analogy this is like asking the operator to dial a number for you In this case you want to address a GPIB device at primary address 1 on the GPIBO bus The value for x in the GPIBx token GPIBO in this example indicates which GPIB board you want This means that you can have multiple GPIB boards installed in the computer each controlling independent buses For more information on address strings viOpen and viOpenDefaultRM see Chapter 4 Initializing Your VISA Application The two VI_NULLs following the address string are not important at this time They specify that the session should be initialized using VISA defaults Finally viopen returns the communication channel to the device in the parameter instr From now on whenever you want to talk to this device you use the instr variable to identify it Notice that you do not use the default RM handle again The main use of defaultRM is to open channels to devices You do not use this handle again until you are ready to end the program At this point you need to set a timeout value for message based communication A timeout value is important in message based communication to determine what should happen when the device stops communicating VISA has acommon function to set values such as these viSetAttribute This function sets values such as timeout and the termination character for the communication channel In thi
130. ribution across networks Interactive Control of VISA NI VISA comes with a utility called VISA Interactive Control VISAIC on all platforms that support VISA with the exception of Macintosh and VxWorks This utility gives you access to all of VISA s functionality interactively in an easy to use graphical environment It is a convenient starting point for program development and learning about VISA When VISAIC runs it automatically finds all of the available resources in the system and lists the instrument descriptors for each of these resources under the appropriate resource type This information is displayed on the VISA I O tab National Instruments Corporation 3 3 NI VISA User Manual Chapter 3 VISA Overview NI VISA User Manual The following figure shows the VISAIC opening window VISA Interactive Control mje x File Edit View Help ST INSTRUMENTS VISA I O Soft Front Panels NII O Nirstrovenrs View By Type View By Connection 2 Em J GPIB2 GPIB ENET L J GPIB2 2 INSTR 5 3 VXI0 PCI MXI 2 34 VXI0 MEMACC ae VAIO 00 INSTR B 34 Mainframe 1 ee dl 334 VIO 20INSTR a F ASRLI COM1 L F ASRL1 INSTR a F ASRL10 LPT1 Resource to Open a The Soft Front Panels tab of the main VISAIC panel gives you the option to launch the soft front panels of any VXIplug amp play instrument drivers that have been installed on the system The NI I O tab gives you the optio
131. rted The Read Me First document included with your kit explains how to install and set up your system Once you have set up your system you can use Chapter 2 to guide yourself through some simple examples Chapters 3 through 8 contain more in depth information about the different elements that make up the VISA system What You Need to Get Started QO National Instruments Corporation Appropriate hardware in the form of a National Instruments GPIB GPIB VXI MXI VXI or serial interface board For serial support the computer s standard serial ports are sufficient NI 488 2 and or NI VXI installed on your system For serial support the system s serial drivers are sufficient NI VISA distribution media If you have a GPIB VXI command module from another vendor you need that vendor s GPIB VXI VISA component It will be installed into the lt VX IPNPPATH gt lt Framework gt bin directory For example the Hewlett Packard component for the HPE1406 would be C VXIpnp Win95 bin HPGPVX32 d11 1 1 NI VISA User Manual Chapter 1 Introduction Introduction to VISA NI VISA User Manual The main objective of the VXIplug amp play Systems Alliance is to increase ease of use for end users of VXI technology through open multivendor VXI systems The alliance members share a common vision for multivendor systems architecture encompassing both hardware and software This common vision enables the members to work togethe
132. ruments configure them and then return its findings to the user The VISA Resource Manager has a similar function It scans the system to find all the devices connected to it through the various interface buses and then controls the access to them Notice that the Resource Manager simply keeps track of the resources and creates sessions to them as requested You do not go through the Resource Manager with every operation defined on a resource Again referring to Example 2 1 notice that the first line of code is a function call to get a session to the Default Resource Manager status viOpenDefaultRM amp defaultRM i Note viOpenDefaultRM is a function call not an operation call An operation is a property of a resource that you call by way of a session The viOpenDefaultRM function returns a unique session to the Default Resource Manager but does not require some other session to operate Therefore this function is not a property of any resource not even the Resource Manager Resource It is provided by the VISA driver itself Now that you have a communication channel session to the Resource Manager you can ask it to create sessions to instruments for you In addition to this VISA also defines operations that can be invoked to query the Resource Manager about other resources it knows about You can use the viFindRsrc operation to give the Resource Manager a search string known as a regular expression for instruments in the s
133. ry as follows status viOutl6 instr VI_A24 SPACE 0x0 0x1234 Thus the offset when using an INSTR resource is 0x0 not 0x200000 VISA also supports sessions to the interface bus itself via the MEMACC Resource Refer to Chapter 6 Register Based Communication for more information about this resource These methods are known as the High Level Access methods to distinguish them from the Low Level Access methods The High Level Access methods encapsulate all the necessary code to perform a read or a write of a register including mapping any necessary access windows and handling errors such as a bus error In contrast the Low Level Access methods do not Instead you map the windows yourself and VISA does not monitor for errors Refer to Chapter 6 Register Based Communication for more information about accessing register based devices with both the High Level Access and the Low Level Access methods National Instruments Corporation 3 11 NI VISA User Manual Chapter 3 VISA Overview Example of Interface Independence NI VISA User Manual Now that you are more familiar with the architecture of the VISA driver look at the GPIB VXI interface board to see if VISA gives you independence from the interface connecting the instruments The GPIB VXI device translates GPIB bus communication to VXIbus communication and vice versa Its main purpose is to let GPIB users add VXI devices to their systems inexpensively Using GPIB driver sof
134. s Notice also that viEnableEvent can add to the number of mechanisms in use during a session For example if you have enabled the application for queuing it can make a subsequent call to viEnableEvent specifying the callback mechanism The end result is that both the queuing and callback mechanisms are enabled You cannot use the viEnableEvent operation to decrease the number of mechanisms on which a session is enabled for sensing Instead you must use viDisableEvent for that purpose For example if you have enabled a session for both vI_QUEUE and VI_HNDLR a subsequent call to viEnableEvent with the mechanism parameter set to VI_QUEUE does not change the mechanism to queuing only but returns with the success code VI_SUCCESS_EVENT_EN meaning that the specified event is enabled for at least one of the specified mechanisms To disable the callback mechanism call viDisableEvent with its mechanism parameter set to VI_HNDLR This action disables the callback mechanism but keeps the queuing method of notification enabled as in the following example status viDisableEvent instr VI_EVENT_VXI_SIGP VI_HNDLR The viEnableEvent operation also automatically enables the hardware if necessary for detecting the event The hardware is enabled when the first call to viEnableEvent for the event is made from any o
135. s queuing mechanism except that you cannot access it directly You can obtain the events on the queue only by re enabling the session for callbacks You can flush the queue with viDiscardEvents For example the following code segment shows how you can halt the arrival of events while you perform some critical operations that would conflict with code in the callback handler Notice that no events are lost while this code executes because they are stored on a queue status viEnableEvent instr VI_EVENT_SERVICE_REQ VI_HNDLR VI_NULL status viEnableEvent instr VI_EVENT_SERVICE_REQ VI_SUSPEND_HNDLR VI_NULL Perform code that must not be interrupted by a callback status viEnableEvent instr VI_EVENT_SERVICE_REQ VI_HNDLR VI_NULL When you switch the event mechanism from VI_HNDLR to VI_SUSPEND_HNDLR the VISA driver can still detect the events For example VXI interrupts still generate a local interrupt on the controller and VISA handles these interrupts However the event VISA generates for the VXI interrupt is now placed on the handler queue rather than passed to the application When the critical section completes switching the mechanism from VI_SUSPEND_HNDLR back to VI_HNDLR causes VISA to call the application s callback functions whenever it detects a new event as well as for every event waiting on the
136. s 9 2 multiple applications using NI VISA driver 9 2 NI VISA User Manual l 4 multiple interface support issues 9 4 to 9 6 multiple GPIB VXI support 9 4 serial port support 9 5 VME support 9 6 VXI and GPIB platforms 9 5 Windows 3 x issues 9 6 to 9 7 application stack size 9 7 installation overview 9 6 memory model 9 6 programming examples event handling 2 7 to 2 10 callbacks 2 7 discussion of example 2 3 2 9 to 2 10 example 2 3 2 8 to 2 9 queuing 2 7 queuing and callback example 7 1 7 9 to 7 11 Visual Basic examples A 4 A 12 to A 13 locking 2 10 to 2 12 discussion of example 2 4 2 12 example 2 4 2 10 to 2 11 example 8 1 8 4 to 8 6 Visual Basic examples A 5 A 14 to A 15 Low Level Access operations 5 9 to 5 10 message based communication 2 1 to 2 4 discussion of example 2 1 2 3 to 2 4 example 2 1 2 2 example 4 1 4 12 to 4 13 overview 2 1 Visual Basic examples A 2 A 6 register based communication 2 4 to 2 7 discussion of example 2 2 2 6 to 2 7 example 2 2 2 5 to 2 6 example 5 1 5 9 to 5 10 overview 2 4 to 2 5 Visual Basic examples A 3 A 7 National Instruments Corporation Resource Manager accessing resources example 6 1 6 2 to 6 3 Visual Basic example A 9 searching for resources example 6 2 6 4 to 6 6 Visual Basic example A 10 to A 11 shared memory operations example 5 2 5 12 to 5 13 Visual Basic example A 8 programming language support for NI VISA table 1 3 to 1
137. s flushed with every call to viPrintf and vivPrintf essentially disabling the buffering mode The read buffer is maintained by the viScanf viVScanf viBufRead and vivQueryf read side operations To explicitly flush the read buffer you can make a call to the viF lush operation with aread flag set The only rule for automatically flushing the read buffer is in response to the viSetBuf operation However as with the write buffer you can use an attribute to control how to flush the buffer VI_ATTR_RD_BUF_OPER_MODE If the attribute is set to VI_FLUSH_DISABLE the buffer is flushed only when an explicit call to viFlush is made If this attribute is set to VI_FLUSH_ON_ACCESS the buffer is flushed at the end of every call to viScanf In addition to the preceding rules and attributes the formatted I O buffers of a session to a given device are reset whenever that device is cleared through the viClear operation At such a time the read and write buffer must be flushed and any ongoing operation through the read write port must be aborted Resizing the Formatted 1 0 Buffers NI VISA User Manual The read and write buffers as mentioned previously can be dynamically resized using the viSetBuf operation Remember that this operation automatically flushes the buffers so it is best to set the size of the buffers before beginning the actual I O calls You specify which buffer you wan
138. s Corporation I O services basic I O services 4 1 to 4 7 asynchronous read write services 4 3 to 4 4 clear services 4 4 to 4 5 status service request service 4 6 to 4 7 synchronous read write services 4 2 to 4 3 trigger services 4 5 to 4 6 formatted I O services 4 7 to 4 11 automatically flushing formatted I O buffers 4 9 to 4 10 controlling serial I O buffers 4 11 formatted I O operations 4 7 to 4 8 manually flushing formatted I O buffers 4 9 resizing formatted I O buffers 4 10 Variable List operations 4 8 L local attributes 3 5 locks 8 1 to 8 6 acquiring exclusive lock 8 3 lock sharing 8 2 to 8 3 nested locks 8 3 overview 8 1 programming examples example 2 4 2 10 to 2 12 example 8 1 8 4 to 8 6 Visual Basic examples A 5 A 14 to A 15 types of locks 8 1 to 8 2 Low Level Access operations 5 5 to 5 10 bus errors 5 10 comparison of high and low level access 5 10 to 5 11 accessing multiple address spaces 5 11 National Instruments Corporation l 3 Index ease of use 5 10 speed 5 10 computer access overview 5 5 to 5 7 example 5 1 5 9 to 5 10 operations versus pointer deference 5 8 overview 3 8 pointer manipulation 5 8 to 5 9 programming considerations for NI VISA 9 1 to 9 4 read and write operations table 5 2 using VISA for performing 5 7 to 5 8 manual See documentation mapping See address mapping memory shared See shared memory operations Memory I O services 5
139. s example notice that the function call to viSetAttribute sets the timeout to be 5 s 5000 ms for both reading and writing strings 2 3 NI VISA User Manual Chapter 2 Introductory Programming Examples 4 Now that you have the communication channel set up you can perform string I O using the viWrite and viRead functions Notice that this is the section of the programming code that is unique for message based communication Opening communication channels as described in steps 1 and 2 and closing the channels as described in step 5 are the same for all VISA programs The parameters that these calls use are relatively straightforward First you identify which device you are talking to with instr b Next you give the string to send or what buffer to put the response in c Finally specify the number of characters you are interested in For more information on these functions see Chapter 5 Message Based Communication Also refer to the NI VISA online help or the NI VISA Programmer Reference Manual 5 When you are finished with your device I O you can close the communication channel to the device with the viClose function Notice that the program shows a second call to viClose When you are ready to shut down the program or at least close down the VISA driver you use viClose to close the communication channel returned by viOpenDefaultRM Example of Register Based Communication r Note NI VISA User Ma
140. s is platform dependent as shown in Table 9 1 National Instruments Corporation 9 3 NI VISA User Manual Chapter 9 NI VISA Platform Specific and Portability Issues NI VISA User Manual Table 9 1 How VISA Invokes Callbacks Platform Callback Invocation Method Windows 3 x The application s stack and data segments are set up properly The callback does not occur from within the driver interrupt service routine Windows 95 The callback is performed in a separate thread Windows NT created by NI VISA The thread is signaled as soon as the event occurs Macintosh 68K For VXI the callback is performed from within the Macintosh PPC driver interrupt service routine For all other interfaces the callback is performed only when the driver is accessed Solaris 2 x For VXI with the PCI MXI 2 the callback is performed in a separate thread For all other interfaces the callback is performed via a UNIX signal VxWorks The callback is performed via a UNIX signal Solaris 1 x HP UX 9 HP UX 10 What this means is that on Windows 3 x all interfaces and Macintosh all interfaces other than VXI you cannot wait in a tight loop for a callback to occur For example the following code does not work while intr_recv 4 do nothing For callbacks to be invoked on these platforms you must call any VISA operation or give up processor time You can do this through any of the following methods listed in
141. s the specified event if it exists in the queue and returns immediately Otherwise the application waits until the specified event occurs or until the timeout expires whichever occurs first When an event arrives and causes viWaitOnEvent to return the event is not queued for the session on which the wait operation was invoked However if any other session is currently enabled for queuing the event is placed on the queue for that session You can use viDisableEvent to disable event queuing on a session as discussed in the previous section If you disable the queue no further event occurrences are queued but event occurrences that were already in the event queue are retained Your application can use viWaitOnEvent to dequeue these retained events in the same manner as previously described The wait operation does not need to have events enabled to work however the session must be enabled to detect new events An application can explicitly clear flush the event queue with the viDiscardEvents operation The event queues in VISA are of fixed length but you can specify the size of a queue by using the VI_LATTR_MAX_QUEUE_LENGTH template attribute This attribute specifies the maximum number of events that can be placed on queue H Note If the event queue is full and a new event arrives the new event is discarded VISA does not currently let you dynamically configure queue lengt
142. s usually used for libraries on Windows platforms An asynchronous occurrence that is independent of the normal sequential execution of the process running in a system First In First Out a method of data storage in which the first element stored is the first one retrieved G 2 National Instruments Corporation handler instrument instrument driver interface interrupt lock mapping 0 operation National Instruments Corporation G 3 Glossary Same as callback A software routine that is invoked when an asynchronous event occurs In VISA callbacks can be installed on any session that processes events A device that accepts some form of stimulus to perform a designated task test or measurement function Two common forms of stimuli are message passing and register reads and writes Other forms include triggering or varying forms of asynchronous control A set of routines designed to control a specific instrument or family of instruments and any necessary related files for LabWindows CVI or LabVIEW A generic term that applies to the connection between devices and controllers It includes the communication media and the device controller hardware necessary for cross communication A condition that requires attention out of the normal flow of control of a program A state that prohibits sessions other than the session s owning the lock from accessing a resource An operation that returns a reference t
143. second session with the same access key ef status viLock instrIN VI_SHARED_LOCK 5000 VI_NULL accKey status viLock instrOUT VI_SHARED_LOCK VI_TMO_IMMEDIATE accKey NI VISA User Manual accKey 8 4 National Instruments Corporation Chapter 8 VISA Locks Set trigger channel for sessions zy status viSetAttribute instrIN VI_ATTR_TRIG_ID VI_TRIG_TTLS status viSetAttribute instrOUT VI_LATTR_TRIG_ID VI_TRIG_TTL4 Enable input session for trigger events status viEnableEvent instrIN VI_EVENT_TRIG VI_QUEUE VI_NULL Assert trigger to tell device to start sampling status viAssertTrigger instrOUT VI_TRIG_PROT_DEFAULT Device will respond with a trigger when data is ready j if status viWaitOnEvent instrIN VI_EVENT_TRIG 20000 amp etype amp event lt VI_SUCCESS viClose defaultRM return 1 Close the event status viClose event Read data from the device xf status viRead instrIN buf MAX_COUNT amp retCount Your code should process the data ay Unlock the sessions status viUnlock instrIN status viUnlock instrOUT Close down the system status viClose instrIN status viClose instrOUT status viClose defaultRM return 0 National Instruments Corporation 8 5 NI VISA User Manual NI VISA Platfor
144. sn VI_ATTR_MANF_ID iManf If stat gt VI_SUCCESS And iManf MANF_ID Then stat viGetAttribute sesn VI_ATTR_MODEL_CODE iModel If stat gt VI_SUCCESS And iModel MODEL_CODE Then Rem We have a match return session without closing instrSesn sesn stat viClose fList Rem Do not close dfltRM that would close sesn too AutoConnect VI_SUCCESS Exit Function End If End If stat viClose sesn End If stat viFindNext fList desc nList nList 1 Wend Rem No match was found return an error stat viClose fList stat viClose df1tRM AutoConnect VI_ERROR_RSRC_NFOUND End Function Example 4 3 Example 4 3 uses functionality not available in Visual Basic Refer to Example 4 2 for sample code using viFindRsrc NI VISA User Manual A 8 National Instruments Corporation Example 5 1 Appendix A Visual Basic Examples Private Sub vbMain Dim stat As ViStatus Dim df1tRM As ViSession Dim sesn As ViSession Dim retCount As Long Dim idnResult As String 72 Dim resultBuffer As String 256 Rem Open Default Resource Manager stat viOpenDefaultRM df1tRM If stat lt VI_SUCCESS Then Rem Error initializing VISA exiting Exit Sub End If Rem Open communication with GPIB Device at Primary Addr 1 Rem NOTE For simplicity
145. ss the VXIbus are a limited resource Call the viMapAddress operation before attempting to perform low level VXIbus access with viPeekxXx or viPokexx Immediately after the accesses are completed always call the viUnmapAddress operation so that you free up the memory window for other applications Low Level Access Functions NI VISA User Manual The viMapAddress operation returns a pointer for use with low level access functions On some systems such as the VXIpc embedded computers it is possible to directly dereference this pointer However on other systems such as the GPIB VXI you must use the viPeekxXx and viPokeXx operations To make your source code portable between these and other platforms and even other implementations of VISA check the attribute VI_ATTR_WIN_ACCESS after calling viMapAddress 9 2 National Instruments Corporation Chapter 9 NI VISA Platform Specific and Portability Issues If the value of that attribute is VI_DEREF_ADDR youcan safely dereference the address pointer directly Otherwise use the viPeekxx and viPokeXxX operations to perform register I O accesses National Instruments also provides macros for viPeekXxX and viPokeXx on certain platforms The C language macros automatically dereference the pointer whenever possible without calling the driver which can substantially improve performance The macros also handle any retry conditions on the new MXI 2 platforms
146. sset Sie E E EE A N beaten inset deeentn cab levee EE ye 5 1 Basic VO Services mironi e tote E e E e A R EE E AA 5 1 Synchronous Read Write Services ees ese csceesecseeeseceeceseceseeeeeeenseeeeeees 5 2 Asynchronous Read Write Services eececesceceseeeeceeeseeeeseeeneeseeeaeenaeeaees 5 3 Clear Service igsisuk etnies RUS en Meee ae ea eta 5 4 TUB POL SEVICE eee S EEE RE E R E a a 5 5 Status Service Request Service esseeseseeeesereeresrsrrssrerrserrrsreerereererrsserrssene 5 6 Formatted VO OV E S aa e a R e AE aC Ea iee SEEE KETSE SE 5 7 Formatted I O Operations 2 00 00 eee eeeecceeseeeceseeesecaeecaeceaeeaeceecseenseseeeeeeaeeees 5 7 TO Butler Operations sisii iseen Ea a e EE RA E 5 8 Variable List Operations eee eee ese eeeceeeeeeeceeeeeecaeesaecaecsaecsecsseeeeseseeseeees 5 8 Manually Flushing the Formatted I O Buffers eee eeeesecneceteeeeees 5 9 Automatically Flushing the Formatted I O Buffers 0 000 eee eeeeeee eres 5 9 Resizing the Formatted I O Buffers 00 0 0 ceeceecnecesecneceeeereeseeneenseees 5 10 Controlling the Serial I O Buffers cece cseseceeceseceseeseceseeeeeeeerees 5 11 Example VISA Message Based Application ccceceeseesceseeeeeseeeeeceeaecsseeaececeseees 5 12 Example S Were cscs etete vn sete tec tee eee ae ee tee 5 12 NI VISA User Manual vi National Instruments Corporation Contents Chapter 6 Register Based Communication TintroduGti on s 23 2s3s5 cacesesiyeshecashe seavest
147. status The most straightforward of the operations are viRead andviWrite which perform the actual receiving and sending of strings Notice that these operations look upon the data as a string and do not interpret the contents For this reason the data could be messages commands or binary encoded data depending on how the device has been programmed For example the TEEE 488 2 command JDN is a message that is sent in ASCII format However an oscilloscope returning a digitized waveform may take each 16 bit data point and put it end to end as a series of 8 bit characters The following code segment shows a program requesting the waveform that the device has captured viWrite instr READ WAVFM CH1 14 amp retCount viRead instr buffer 1024 amp retCount Now the character array buffer contains the data for the waveform but you still do not know how the data is formatted For example if the data points were 2 3 the buffer might be formatted as 1 2 3 However if the data were binary encoded 8 bit values the first byte of buf fer would be 1 not the ASCII character 1 but the actual value 1 The next byte would be neither a comma nor the ASCII character 2 but the actual value 2 and so on Refer to the documentation that came with the device for information on how to program the device and interpret the responses The various ways that a string can be sent is the next issue to consider in message based
148. sult 72 ViChar resultBuffer 256 ViStatus status Open Default Resource Manager status viOpenDefaultRM amp defaultRM if status lt VI_SUCCESS Error Initializing VISA exiting ay return 1 Open communication with GPIB Device at Primary Addr 1 aA NOTE For simplicity we will not show error checking viOpen defaultRM GPIB 1 INSTR VI_NULL VI_NULL amp instr Initialize the timeout attribute to 10 s viSetAttribute instr VI_ATTR_TMO_VALUE 10000 Set termination character to carriage return r 0x0D a viSetAttribute instr VI_ATTR_TERMCHAR 0x0D viSetAttribute instr VI_ATTR_TERMCHAR_EN VI_TRUE Don t assert END on the last byte xf viSetAttribute instr VI_ATTR_SEND_END_EN VI_FALSE Clear the devic E viClear instr Request the IEEE 488 2 identification information R viWrite instr IDN n 6 amp retCount viRead instr idnResult 72 amp retCount NI VISA User Manual 5 12 National Instruments Corporation Chapter 5 Message Based Communication Use idnResult and retCount to parse device info Trigger the device for an instrument reading xj viAssertTrigger instr VI_TRIG_PROT_DEFAULT Receive results Ef viRead instr resultBuffer 256 amp retCount Close sessions xy viClose instr viClose defaultRM return 0 National
149. supports only the callback model Refer to the Exception Handling section at the end of this chapter for more information about this event type VISA events use a list of attributes to maintain information associated with the event You can access the event attributes using the viGetAttribute operation just as for the session and resource attributes All VISA events support the generic event attribute VI_ATTR_EVENT_TYPE This attribute provides the type of the event whether Service Request VXI Signal Processor VXI VME Interrupt VXIbus Trigger or I O Completion or Exception 7 2 National Instruments Corporation Chapter 7 VISA Events In addition to this attribute individual events may define attributes to hold additional event information Currently only the VI_EVENT_SERVICE_REQ event does not define additional attributes e VI_EVENT_VXI_SIGP defines VI_LATTR_SIGP_STATUS_ID which contains the 16 bit Status ID value retrieved during the interrupt or from the Signal register the trigger line on which the trigger was received e VI_EVE RIG defines VI_LATTR_RECV_TRIG_ID which provides VI_ATTR_STATUS and VI_ATTR_RET_COUNT which provide information about how the asynchronous I O operation completed e VI_EVE IO_COMPLETION defines among other attributes e VI_EVE VXI_VME_INTR defines VI_ATTR_INTR_STATUS_ID and VI_ATTR_REC
150. t to modify and then the size of the buffer you require It is important to check the return code of this operation because you may be requesting a buffer beyond the size that the system can allocate at the time If this occurs the buffer size is not changed 5 10 National Instruments Corporation Chapter 5 Message Based Communication For example to set both the read and write buffers to 8 KB use the following code status viSetBuf instr VI_READ_BUF VI_WRITE_BUF 8192 Controlling the Serial 1 0 Buffers The viFlush and viSetBuf operations also provide a control mechanism for the low level serial driver buffers The default size of these buffers is 0 which guarantees that all I O is flushed on every access To improve performance you can alter the size of the output or input serial buffers by invoking the viSetBuf operation with the VI_ASRL_OUT_BUF or VI_ASRL_IN_BUF flag respectively When the buffer size is non zero I O to serial devices is not automatically flushed You can force the output serial buffer to be flushed by invoking the viFlush operation with VI_ASRL_OUT_BUF Alternatively you can call viFlush with VI_LASRL_OUT_BUF_DISCARD to empty the output serial buffer without sending any remaining data to the device You can also call viFlush with either VI_ASRL_IN_BUF or VI_ASRL_IN_BUF_DISCARD to empty the input serial buffer both flags have the same effect and are provided only for API consistency
151. t also denotes text from which you supply the appropriate word or value as in Windows 3 x Text in this font denotes text or characters that you should literally enter from the keyboard sections of code programming examples and syntax examples This font is also used for the proper names of disk drives paths directories programs subprograms subroutines device names functions operations variables filenames and extensions and for statements and comments taken from programs Bold text in this font denotes the messages and responses that the computer automatically prints to the screen This font also emphasizes lines of code that are different from the other examples Italic text in this font denotes that you must enter the appropriate words or values in the place of these items Paths in this manual are denoted using backslashes to separate drive names directories folders and files X National Instruments Corporation About This Manual How to Use This Document Set Use the documentation that came with your GPIB and or VXI hardware and software for Windows to install and configure your system Refer to the Read Me First document for information on installing the NI VISA distribution media Use the NI VISA User Manual for detailed information on how to program using VISA Use the NI VISA online help or the NI VISA Programmer Reference Manual for specific information about the attributes events and operatio
152. th a single VXI device In addition because a VXI device can export memory in either A24 or A32 space but not both the memory pool available to these operations is defined at startup You can determine whether the memory resides in A24 or A32 space by querying the attribute VI_LATTR_MEM_SPACE National Instruments Corporation 6 11 NI VISA User Manual Chapter 6 Register Based Communication Shared Memory Sample Code The following example shows how these shared memory operations work by incorporating them into Example 6 1 Their main purpose is to allocate a block of memory from the pool that can then be accessed through the standard register based access operations high level or low level The INSTR resource for this device ensures that no two sessions requesting memory receive overlapping blocks CF Note Example 6 2 uses bold text to distinguish lines of code that are different from those in Example 6 1 Example 6 2 include visa h define ADD_OFFSET addr offs ViPByte addr offs int main void viStatus status For checking errors ViSession defaultRM self Communication channels kf ViAddr address User pointer ViBusAddress offset Shared memory offset ViUInt16 addrSpace Shared memory space ViUInt16 value To store register value Begin by initializing the system a status viOpenDefaultRM amp defaultRM if status lt VI_SUCCESS Error Init
153. th a trigger when data is ready tat viWaitOnEvent sesnIN VI_EVENT_TRIG 20000 etype event f stat lt VI_SUCCESS Then stat viClose df1tRM Exit Sub NI VISA User Manual A 14 National Instruments Corporation Appendix A Visual Basic Examples End If Rem Close the event stat viClose event Rem Read data from the device stat viRead sesnIN buf MAX_COUNT retCount Rem Your code should process the data Rem Unlock the sessions stat viUnlock sesnIN stat viUnlock sesnOUT Rem Close down the system stat viClose sesnIN stat viClose sesnOUT stat viClose df1tRM End Sub National Instruments Corporation A 15 NI VISA User Manual Customer Communication For your convenience this appendix contains forms to help you gather the information necessary to help us solve your technical problems and a form you can use to comment on the product documentation When you contact us we need the information on the Technical Support Form and the configuration form if your manual contains one about your system configuration to answer your questions as quickly as possible National Instruments has technical assistance through electronic fax and telephone systems to quickly provide the information you need Our electronic services include a bulletin board service an FTP site a fax on demand system and e mail support If you have a hardware or software problem first try
154. the electronic support systems If the information available on these systems does not answer your questions we offer fax and telephone support through our technical support centers which are staffed by applications engineers 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 United States 512 794 5422 Up to 14 400 baud 8 data bits 1 stop bit no parity United Kingdom 01635 551422 Up to 9 600 baud 8 data bits 1 stop bit no parity France 01 48 65 15 59 Up to 9 600 baud 8 data bits 1 stop bit no parity 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 National Instruments Corporation B 1 NI VISA User Manual Fax on Demand Support Fax on Demand is a 24 hour information retrieval system containing a library of documents on a wide range of technical information You can access Fax on Demand from a touch tone telephone at 512
155. the VXIplug amp play binary directory C VXIPNP WIN BIN by default to the PATH environment variable in AUTOEXEC BAT and setting the VPNPPATH environment variable in both files to the root of the VXIplug amp play directory tree C by default Memory Model The NI VISA driver was compiled using the large memory model However Windows application programs that link with the VISA library can also use the medium compact or small memory models Because of this ability to use different memory models for your application not only can you take advantage of the efficiency inherent in small memory model programs but you can also run multiple instances of the application Application Stack Size The default stack size in Borland C is 5 KB and in Microsoft Visual C it is 2 KB In VISA where the invocation of an operation may make other calls that in turn call a lower level driver such as NI V XI or NI 488 2 such a small stack may easily be exhausted resulting in a stack overflow For Windows 3 x 16 bit VISA applications set the stack size to a minimum of 8 KB using the STACKSIZE statement in the application s DEF file In LabWindows CVI for Windows 3 x the stack size is not normally a problem as the default stack size is set to a more reasonable 16 KB National Instruments Corporation 9 7 NI VISA User Manual Visual Basic Examples This appendix shows the Visual Basic syntax of the ANSI C examples
156. the data Rem Close down the system stat viClose sesn stat viClose df1tRM End Sub NI VISA User Manual A 2 National Instruments Corporation Appendix A Visual Basic Examples Example 2 2 Private Dim Dim Dim Dim Rem stat PEN seat Sub vbMain stat As ViStatus df1tRM As ViSession sesn As ViSession deviceID As Integer Begin by initializing the system viOpenDefaultRM df1tRM stat lt VI_SUCCESS Then Rem Error initializing VISA exiting Exit Sub If Open communication with VXI Device at Logical Addr 16 NOTE For simplicity we will not show error checking viOpen df1ltRM VXI0O 16 INSTR VI_NULL VI_NULL sesn Stat Stat Stat Stat Read the Device ID and write to memory in A24 space vilInl6 sesn VI_A16_SPACE 0 devicelID viOutl 6 sesn VI_A24_ SPACE 0 amp H1234 Close down the system viClose sesn viClose df1tRM National Instruments Corporation A 3 NI VISA User Manual Appendix A Visual Basic Examples Example 2 3 Private Sub vbMain Dim stat As ViStatus Dim dfltRM As ViSession Dim sesn As ViSession Dim eType As ViEventType Dim eData As ViEvent Dim statID As Integer Rem Begin by initializing the system stat viOpenDefaultRM df1tRM If stat lt VI_SUCCESS Then Rem Error initializing VISA exiting Exit Sub End If Rem Open communication with VXI Device at Logical Address 16
157. ts can be instructed to wait until they receive a trigger before they start performing operations such as generating a waveform reading a voltage and so on Under GPIB this trigger is a software command sent to the device Under VXI this could either be a software trigger or a hardware trigger on one of the multiple TTL ECL trigger lines on the VXIbus backplane VISA uses the same operation viAssertTrigger to perform these actions Which trigger method software or hardware you use is dependent on a combination of an attribute VI_LATTR_TRIG_ID and a parameter to the operation For example to send a software trigger by default under either interface you use the following code status viSetAttribute instr VI_ATTR_TRIG_ID VI_TRIG_SW status viAssertTrigger instr VI_TRIG_PROT_DEFAULT Of course you need to set the attribute only once at the beginning of the program not every time you assert the trigger If you want to assert a VXI hardware trigger such as a SYNC pulse you can use the following code status viSetAttribute instr VI_ATTR_TRIG_ID VI_TRIG_TTL3 status viAssertTrigger instr VI_TRIG_PROT_SYNC Keep in mind that VISA currently uses device triggering That is each call to viAssertTrigger is associated with a specific device through the session used in the call Future versions of VISA will give you full access to interface triggering but at this time all functionality is defi
158. tware you can communicate with VXI devices using messages the same way you program stand alone GPIB instruments But how do you perform register accesses to the VXI devices Up to this point you were required to send messages to the GPIB VXI itself and ask it to perform the register access It would then return the result of the I O in another string For example when talking to the National Instruments GPIB VXI C with NI 488 2 the register access looks like the following when using NI 488 function calls dev ibdev boardID PrimAddr SecAddr TMO EOT EOS status ibwrt dev A24 h200000 h1234 cnt If you are using NI 488 2 routines the same call is Send boardID Address A24 h200000 h1234 DABend If you had ever planned to move your code to a MXI or embedded VXI controller solution you would spend a great deal of time changing your GPIB calls to VXI calls especially when considering register accesses VISA has been designed to eliminate problems such as this limitation If you are talking to a VXI instrument you can perform register I O regardless of whether you are connected via GPIB MXI or an embedded VXI computer In addition the code is the same for all three cases Therefore the code for writing to the A24 register through a GPIB VXI is now precisely the same as given previously in the Register Communication section status viOut16 instr VI_A24_ SPACE 0x0 0x1234 The fact that G
159. ual 5 6 National Instruments Corporation Chapter 5 Message Based Communication Formatted 1 0 Services The Formatted I O Services perform formatted and buffered I O for devices A formatted write operation writes to a buffer inside the driver while a formatted read operation reads from a buffer inside the driver Buffering improves system performance by having the driver perform the T O with the device only at certain times such as when the buffer is full The driver is then able to send larger blocks of information to the device at a time improving overall throughput The buffer operations also provide control over the low level serial driver buffers See the section Controlling the Serial I O Buffers later in this chapter for more information on that topic Formatted 1 0 Operations The main two operations under the formatted I O services are viPrintf and viScanf Although this section discusses these two operations only this material also applies to other formatted I O routines such as viVPrintf and vivScanf These operations derive their names from the standard C string I O functions Like print f and scanf these operations let you use special format strings to dynamically create or parse the string For example a common command for instruments is the Fx command for function x This could be F1 for volt measurement F2 for ohm measurement and so on With formatted I O you can select the type of measureme
160. ug amp play products are classified within a framework The concept of a framework was developed by the VXIplug amp play Systems Alliance to categorize operating systems programming languages and I O software libraries to bring the most useful products to the most end users A framework is a logical grouping of the choices that you face when designing a test and measurement system You must always choose an operating system and a programming language along with an application development environment ADE when building a system There are trade offs associated with each of these decisions many configurations are possible The VXIplug amp play Systems Alliance grouped the most popular 1 2 National Instruments Corporation Chapter 1 Introduction operating systems ADEs and programming languages into distinct frameworks and defined in depth specifications to guarantee interoperability of the components within each framework This manual describes how to use NI VISA the National Instruments implementation of the VISA I O standard in any environment using LabWindows CVI any ANSI C compiler or Microsoft Visual Basic NI VISA currently supports the frameworks and programming languages shown in Table 1 1 For information on programming VISA from LabVIEW refer to the VISA documentation included with your LabVIEW software Table 1 1 NI VISA Support Programming Language Operating System Env
161. viBufRead which reads the string from the instrument into a user specified buffer Then use viSScanf to extract information from the buffer Similarly you can format a buffer with viSPrintf and then use viBufWrite to send it to an instrument As you can see the formatted I O approach is the simplest way to get the job done Because of the variety of modifiers you can use in the format string this section does not go into any more detail on these operations Please refer either to the NI VISA online help or to Chapter 5 Operations in the NI VISA Programmer Reference Manual for more information Variable List Operations You can also use another form of the standard formatted I O operations known as Variable List operations vivPrintf viVSPrintf vivScanf viVSScanf and vivQueryf These functions are identical in their operation to the ANSI C versions of variable list operations Please see your C reference guide for more information NI VISA User Manual 5 8 National Instruments Corporation Chapter 5 Message Based Communication Manually Flushing the Formatted 1 0 Buffers This section describes flushing issues that are related to formatted I O buffers The descriptions apply to all buffered read and buffered write operations For example the viPrintf description applies equally to other buffered write operations vivPrintf and viBufWrite Similarly the viScanf description applies to other buff
162. viEnableEvent operation asynchronous read write services example 4 4 callback modes example 7 6 to 7 7 enabling events 7 3 to 7 4 programming example 2 3 2 8 2 9 VI_EVENT_IO_COMPLETION event 7 2 VI_LEVENT_SERVICE_REQ event 4 6 7 2 VI_LEVENT_TRIG event 7 2 VI_EVENT_VXI_SIGP event 7 2 viFindNext operation example 6 5 6 6 viFindRsrc operation searching for resources example 6 4 to 6 5 6 6 specifying regular expression for Resource Manager 3 7 viFlush operation automatically flushing formatted I O buffers 4 9 controlling serial I O buffers 4 11 manually flushing formatted I O buffers 4 9 viGetAttribute operation event context with callback mechanism 7 11 programming example 2 3 2 9 service request example 4 6 viln8 viln16 viln32 operations High Level Access operations 5 2 to 5 3 National Instruments Corporation opening Resource Manager communications example 3 7 programming example 2 2 2 5 2 6 requirements for accessing registers 5 3 vilnstallHandler operation 7 6 7 7 9 3 viLock operation acquiring exclusive lock 8 3 lock sharing 8 2 nested locks 8 3 programming example 2 4 2 11 2 12 sample code 8 5 viMapAddress operation calling before using viPeekXX or viPokeXX 9 2 performing low level register accesses 5 7 9 2 pointer dereferencing vs operations 5 8 pointer manipulation 5 8 to 5 9 viMemAlloc operation programming example 5 13 shared memory operation 5 11 viMemFr
163. vide quality products to meet your needs Title NI VISA User Manual Edition Date June 1998 Part Number 321074D 01 Please comment on the completeness clarity and organization of the manual If you find errors in the manual please record the page numbers and describe the errors Thank you for your help Name Title Company Address E Mail Address Phone Fax Mail to Technical Publications Faxto Technical Publications National Instruments Corporation National Instruments Corporation 6504 Bridge Point Parkway 512 794 5678 Austin Texas 78730 5039 Glossary Prefix Meanings Value p pico 10 2 n nano 10 9 u micro 10 6 m milli 10 3 k kilo 103 M mega 10 G giga 10 t tera 10 A address location address string API attribute Refers to the location of a specific register A string or other language construct that uniquely locates and identifies a resource VISA defines an ASCIH based grammar that associates strings with particular physical devices and VISA resources Application Programming Interface The direct interface that an end user sees when creating an application In VISA the API consists of the sum of all of the operations attributes and events of each of the VISA resource classes A value within an object or resource that reflects a characteristic of
164. y VISA resource manager This is the name given to the part of VISA that manages resources This management includes support for finding resources and opening sessions to them VISA resource template This is the name given to the part of VISA that defines the basic constraints and interface definition for the creation and use of a VISA resource All VISA resources must derive their interface from the definition of the VISA Resource Template This includes services for setting and retrieving attributes receiving events locking resources and closing objects NI VISA User Manual G 6 National Instruments Corporation Index A address mapping accessing multiple address spaces 5 11 operation versus pointer dereference 5 8 overview of register accesses from computers 5 5 to 5 7 performing low level register accesses 5 6 to 5 7 pointer manipulation 5 8 to 5 9 programming example 5 9 to 5 10 application stack size under Windows 3 x 9 7 asynchronous read write services 4 3 to 4 4 attributes definition 3 4 global 3 5 local 3 5 basic I O services 4 1 to 4 7 asynchronous read write services 4 3 to 4 4 clear services 4 4 to 4 5 status service request service 4 6 to 4 7 synchronous read write services 4 2 to 4 3 trigger services 4 5 to 4 6 buffers automatically flushing formatted I O buffers 4 9 to 4 10 controlling serial I O buffers 4 11 manually flushing formatted I O buffers 4 9 resizing formatted I O buffers
165. ype As ViEventType To identify event Dim event As ViEvent To hold event info Dim retCount As Long To hold byte count Rem Begin by initializing the system stat viOpenDefaultRM df1tRM If stat lt VI_SUCCESS Then Rem Error initializing VISA exiting Exit Sub End If Rem Open communications with VXI Device at Logical Addr 16 stat viOpen df1ltRM VXI0 16 INSTR VI_NULL VI_NULL sesnIN stat viOpen df1ltRM VXI0 16 INSTR VI_NULL VI_NULL sesnOUT Rem We open two sessions to the same device Rem One session is used to assert triggers on L channel 4 Rem The second is used to receive triggers on L channel 5 Rem Lock first session as shared have VISA generate the key Rem Then lock the second session with the same access key stat viLock sesnIN VI_SHARED_LOCK 5000 aKey stat viLock sesnOUT VI_SHARED_LOCK VI_TMO_IMMEDIATE aKey aKey T Rem Set trigger channel for sessions stat viSetAttribute sesnIN VI_ATTR_TRIG_ID VI_TRIG L5 s viSetAttribute sesnOUT VI_ATTR_TRIG_ID VI_TRIG L4 ct w ct ll Rem Enable input session for trigger events stat viEnableEvent sesnIN VI_EVENT_TRIG VI_QUEUE VI_NULL Rem Assert trigger to tell device to start sampling stat viAssertTrigger sesnOUT VI_TRIG_PROT_DEFAULT em Device will respond wi
166. ystem See Chapter 4 Initializing Your VISA Application for more information about viFindRsrc NI VISA User Manual 3 10 National Instruments Corporation Chapter 3 VISA Overview Register Communication Now that you know more about communicating with message based devices you can move on to register communication The only types of devices VISA supports that can export register accesses are VXI and PXI devices However VISA has defined these resources to be expandable to other types of devices in the future Refer to Example 2 2 in Chapter 2 Introductory Programming Examples You open communication to the Resource Manager and the resource in the same manner as in Example 2 1 but this time you specify a VXI device This example uses what are known as the High Level Access methods to read and write registers For example if you want to read a 16 bit register say the ID register of the device use the following call status vilInl6 instr VI_A1l6_SPACE 0x0 amp devicelID Notice that the offset requested is 0 This is the offset of the ID register for a VXI device but it is not the absolute address of the register in A16 space This is because instr is a session to the instrument not to the VXI memory space therefore all offsets are from the base address of the instrument For example if this same device also shared its memory in A24 space at 0x200000 you could write to the first memory location of this shared memo

Download Pdf Manuals

image

Related Search

Related Contents

Rockwell L24 Instructions / Assembly  CVS mode d`emploi.pub  く ぎ 固 定 !!! 接 着 !!!  会話器 - インコア  Télécharger  SERVICE MANUAL  009262ex - Bredent  Lenovo ThinkPad 1839 32GB Black  Manual - Boss Audio Systems  Toshiba 26AV502R/Z LCD TV  

Copyright © All rights reserved.
Failed to retrieve file