Example of Locking

NI-VISA

Example of Locking

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 Lock Sharing for more information. The following example uses the simpler form, the exclusive lock, to prevent other VISA applications from modifying the state of the specified serial port.

Example

Note  The following example uses bold text to distinguish lines of code that are different from the other introductory programming examples.

#include "visa.h"

#define MAX_CNT 200

int main(void)
{

ViStatus
ViSession
ViUInt32
ViChar
status;
defaultRM, instr;
retCount;
buffer[MAX_CNT];
/* For checking errors */
/* Communication channels */
/* Return count from string I/O */
/* Buffer for string I/O */
/* Begin by initializing the system */
status = viOpenDefaultRM(&defaultRM);
if (status < VI_SUCCESS) {

/* Error Initializing VISA...exiting */
return -1;

}

/* Open communication with Serial Port 1 */
/* NOTE: For simplicity, we will not show error checking */
status = viOpen(defaultRM, "ASRL1::INSTR", VI_NULL, VI_NULL, &instr);

/* Set the timeout for message-based communication */
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);

/* Set this attribute for binary transfers, skip it for this text example */
/* status = viSetAttribute(instr, VI_ATTR_ASRL_END_IN, 0); */

/* Ask the device for identification */
status = viWrite(instr, "*IDN?\n", 6, &retCount);
status = viRead(instr, buffer, MAX_CNT, &retCount);

/* Unlock 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;

}

Visual Basic Example

Example Discussion