0
# GPIB Communication
1
2
General Purpose Interface Bus (GPIB/IEEE 488) communication for controlling GPIB instruments with support for bus management, device addressing, and control operations. PyVISA-py provides comprehensive GPIB support through linux-gpib and gpib-ctypes backends with automatic device discovery and proper bus control.
3
4
## Capabilities
5
6
### GPIBSessionDispatch Class
7
8
Main dispatcher for GPIB instrument communication that automatically creates the appropriate session implementation (native GPIB or Prologix adapter) based on the GPIB board configuration.
9
10
```python { .api }
11
class GPIBSessionDispatch:
12
"""Dispatcher that creates native GPIB or Prologix sessions based on board configuration."""
13
14
def __new__(cls, resource_manager_session, resource_name, parsed, open_timeout):
15
"""
16
Create appropriate GPIB session based on board configuration.
17
18
Args:
19
resource_manager_session (VISARMSession): Parent RM session
20
resource_name (str): GPIB resource name
21
parsed (rname.ResourceName): Parsed resource name
22
open_timeout (int): Connection timeout in milliseconds
23
24
Returns:
25
GPIBSession or PrologixInstrSession: Implementation-specific session
26
"""
27
```
28
29
### GPIBSession Class
30
31
Native GPIB instrument communication using linux-gpib or gpib-ctypes drivers with full IEEE 488.2 protocol support.
32
33
```python { .api }
34
class GPIBSession:
35
"""Session for native GPIB instrument communication."""
36
37
def __init__(self, resource_manager_session, resource_name, parsed, open_timeout):
38
"""
39
Initialize GPIB instrument session.
40
41
Args:
42
resource_manager_session (VISARMSession): Parent RM session
43
resource_name (str): GPIB resource name (e.g., "GPIB0::10::INSTR")
44
parsed (rname.ResourceName): Parsed resource name
45
open_timeout (int): Connection timeout in milliseconds
46
"""
47
48
def read(self, count):
49
"""
50
Read data from GPIB instrument.
51
52
Args:
53
count (int): Maximum number of bytes to read
54
55
Returns:
56
Tuple[bytes, StatusCode]: Data read and operation status
57
"""
58
59
def write(self, data):
60
"""
61
Write data to GPIB instrument.
62
63
Args:
64
data (bytes): Data to transmit
65
66
Returns:
67
Tuple[int, StatusCode]: Number of bytes written and status
68
"""
69
70
def gpib_command(self, command_byte):
71
"""
72
Send GPIB command bytes (ATN asserted).
73
74
Args:
75
command_byte (bytes): GPIB command bytes to send
76
77
Returns:
78
Tuple[int, StatusCode]: Bytes written and status
79
"""
80
81
def read_stb(self):
82
"""
83
Read status byte from GPIB device.
84
85
Returns:
86
Tuple[int, StatusCode]: Status byte value and operation status
87
"""
88
89
def clear(self):
90
"""
91
Clear GPIB device (send Device Clear command).
92
93
Returns:
94
StatusCode: Operation result
95
"""
96
97
def close(self):
98
"""
99
Close GPIB session and release device.
100
101
Returns:
102
StatusCode: Operation result
103
"""
104
105
@staticmethod
106
def list_resources():
107
"""
108
List available GPIB instruments.
109
110
Returns:
111
List[str]: List of GPIB instrument resource strings
112
"""
113
```
114
115
### GPIBInterface Class
116
117
Provides GPIB bus controller operations for managing the GPIB bus and controlling multiple devices.
118
119
```python { .api }
120
class GPIBInterface:
121
"""Session for GPIB interface/controller operations."""
122
123
def __init__(self, resource_manager_session, resource_name, parsed, open_timeout):
124
"""
125
Initialize GPIB interface session.
126
127
Args:
128
resource_manager_session (VISARMSession): Parent RM session
129
resource_name (str): GPIB interface resource name (e.g., "GPIB0::INTFC")
130
parsed (rname.ResourceName): Parsed resource name
131
open_timeout (int): Connection timeout in milliseconds
132
"""
133
134
def gpib_send_ifc(self):
135
"""
136
Pulse Interface Clear (IFC) line for at least 100 microseconds.
137
138
Returns:
139
StatusCode: Operation result
140
"""
141
142
def gpib_control_ren(self, mode):
143
"""
144
Control state of Remote Enable (REN) interface line.
145
146
Args:
147
mode (constants.RENLineOperation): REN line operation
148
149
Returns:
150
StatusCode: Operation result
151
"""
152
153
def gpib_control_atn(self, mode):
154
"""
155
Control state of Attention (ATN) line.
156
157
Args:
158
mode (constants.ATNLineOperation): ATN line operation
159
160
Returns:
161
StatusCode: Operation result
162
"""
163
164
def gpib_pass_control(self, primary_address, secondary_address):
165
"""
166
Pass controller in charge (CIC) to another device.
167
168
Args:
169
primary_address (int): Primary address of new controller
170
secondary_address (int): Secondary address (or VI_NO_SEC_ADDR)
171
172
Returns:
173
StatusCode: Operation result
174
"""
175
```
176
177
### GPIB Bus Management
178
179
Operations for managing GPIB bus state, addressing, and device control.
180
181
```python { .api }
182
# GPIB addressing constants
183
VI_NO_SEC_ADDR = 0xFFFF # No secondary address
184
185
# REN line operations
186
VI_GPIB_REN_DEASSERT = 0 # Deassert REN line
187
VI_GPIB_REN_ASSERT = 1 # Assert REN line
188
VI_GPIB_REN_DEASSERT_GTL = 2 # Deassert REN and send GTL
189
VI_GPIB_REN_ASSERT_ADDRESS = 3 # Assert REN and address device
190
VI_GPIB_REN_ASSERT_LLO = 4 # Assert REN and send LLO
191
192
# ATN line operations
193
VI_GPIB_ATN_DEASSERT = 0 # Deassert ATN line
194
VI_GPIB_ATN_ASSERT = 1 # Assert ATN line
195
VI_GPIB_ATN_DEASSERT_HANDSHAKE = 2 # Deassert ATN with handshake
196
VI_GPIB_ATN_ASSERT_IMMEDIATE = 3 # Assert ATN immediately
197
```
198
199
## Usage Examples
200
201
### Basic GPIB Instrument Communication
202
203
```python
204
import pyvisa
205
206
# Use PyVISA-py backend
207
rm = pyvisa.ResourceManager('@py')
208
209
# List GPIB instruments
210
gpib_resources = rm.list_resources('GPIB?*::INSTR')
211
print("GPIB instruments:", gpib_resources)
212
213
# Resource string format: GPIB[board]::primary_address[::secondary_address]::INSTR
214
# Examples: "GPIB0::10::INSTR", "GPIB0::5::2::INSTR" (with secondary address)
215
216
if gpib_resources:
217
try:
218
# Open GPIB instrument at primary address 10
219
inst = rm.open_resource("GPIB0::10::INSTR")
220
221
# Configure timeout
222
inst.timeout = 5000 # 5 seconds
223
224
# Standard IEEE 488.2 communication
225
idn = inst.query("*IDN?")
226
print("Instrument ID:", idn.strip())
227
228
# Reset and clear instrument
229
inst.write("*RST")
230
inst.write("*CLS")
231
232
# Check operation complete
233
inst.write("*OPC?")
234
opc = inst.read()
235
print("Operation complete:", opc.strip())
236
237
# Read measurement
238
inst.write("READ?")
239
measurement = float(inst.read())
240
print(f"Measurement: {measurement}")
241
242
except pyvisa.VisaIOError as e:
243
print(f"GPIB communication error: {e}")
244
finally:
245
inst.close()
246
247
rm.close()
248
```
249
250
### GPIB Bus Controller Operations
251
252
```python
253
# Open GPIB interface for bus control operations
254
try:
255
gpib_intfc = rm.open_resource("GPIB0::INTFC")
256
257
# Send Interface Clear to reset bus
258
gpib_intfc.send_ifc()
259
print("Interface Clear sent")
260
261
# Assert Remote Enable for all devices
262
gpib_intfc.control_ren(pyvisa.constants.VI_GPIB_REN_ASSERT)
263
print("REN asserted")
264
265
# Address device at primary address 5
266
gpib_intfc.control_ren(pyvisa.constants.VI_GPIB_REN_ASSERT_ADDRESS)
267
268
# Send Group Execute Trigger to all devices
269
gpib_intfc.assert_trigger(pyvisa.constants.VI_TRIG_PROT_ON)
270
271
# Return devices to local control
272
gpib_intfc.control_ren(pyvisa.constants.VI_GPIB_REN_DEASSERT_GTL)
273
print("Devices returned to local control")
274
275
except pyvisa.VisaIOError as e:
276
print(f"GPIB interface error: {e}")
277
finally:
278
gpib_intfc.close()
279
```
280
281
### Multi-Device GPIB Communication
282
283
```python
284
# Communicate with multiple GPIB devices
285
devices = {
286
"DMM": "GPIB0::3::INSTR", # Digital multimeter
287
"PSU": "GPIB0::5::INSTR", # Power supply
288
"GEN": "GPIB0::10::INSTR", # Function generator
289
}
290
291
instruments = {}
292
293
try:
294
# Open all devices
295
for name, resource in devices.items():
296
inst = rm.open_resource(resource)
297
inst.timeout = 3000
298
instruments[name] = inst
299
300
# Verify communication
301
idn = inst.query("*IDN?")
302
print(f"{name}: {idn.strip()}")
303
304
# Configure instruments
305
instruments["PSU"].write("VOLT 5.0") # Set 5V output
306
instruments["PSU"].write("CURR 1.0") # Set 1A limit
307
instruments["PSU"].write("OUTP ON") # Enable output
308
309
instruments["GEN"].write("FREQ 1000") # Set 1kHz frequency
310
instruments["GEN"].write("VOLT 1.0") # Set 1V amplitude
311
instruments["GEN"].write("OUTP ON") # Enable output
312
313
# Make measurement
314
instruments["DMM"].write("MEAS:VOLT:DC?")
315
voltage = float(instruments["DMM"].read())
316
print(f"Measured voltage: {voltage} V")
317
318
# Turn off outputs
319
instruments["PSU"].write("OUTP OFF")
320
instruments["GEN"].write("OUTP OFF")
321
322
except pyvisa.VisaIOError as e:
323
print(f"Multi-device error: {e}")
324
finally:
325
# Close all instruments
326
for inst in instruments.values():
327
inst.close()
328
```
329
330
### GPIB Status and Error Handling
331
332
```python
333
# Check GPIB device status and handle errors
334
inst = rm.open_resource("GPIB0::10::INSTR")
335
336
try:
337
# Clear status registers
338
inst.write("*CLS")
339
340
# Send command that might cause error
341
inst.write("INVALID:COMMAND")
342
343
# Check for errors using status byte
344
stb = inst.read_stb()
345
print(f"Status byte: 0x{stb:02X}")
346
347
# Check error queue if error bit set
348
if stb & 0x04: # Error queue not empty
349
error = inst.query("SYST:ERR?")
350
print(f"Device error: {error.strip()}")
351
352
# Check for Standard Event Status
353
if stb & 0x20: # ESB bit set
354
esr = int(inst.query("*ESR?"))
355
print(f"Event Status Register: 0x{esr:02X}")
356
357
if esr & 0x20: # Command error
358
print("Command error detected")
359
if esr & 0x04: # Query error
360
print("Query error detected")
361
362
# Wait for operation complete
363
inst.write("*OPC")
364
while True:
365
stb = inst.read_stb()
366
if stb & 0x01: # OPC bit set
367
break
368
time.sleep(0.1)
369
370
except pyvisa.VisaIOError as e:
371
print(f"Status check error: {e}")
372
finally:
373
inst.close()
374
```
375
376
### GPIB Device Discovery and Addressing
377
378
```python
379
def scan_gpib_bus(board=0, max_address=30):
380
"""Scan GPIB bus for responding devices."""
381
rm = pyvisa.ResourceManager('@py')
382
found_devices = []
383
384
for address in range(1, max_address + 1):
385
resource_name = f"GPIB{board}::{address}::INSTR"
386
try:
387
# Try to open device
388
inst = rm.open_resource(resource_name)
389
inst.timeout = 1000 # Short timeout for scanning
390
391
# Try to communicate
392
idn = inst.query("*IDN?")
393
found_devices.append({
394
'address': address,
395
'resource': resource_name,
396
'id': idn.strip()
397
})
398
399
inst.close()
400
401
except pyvisa.VisaIOError:
402
# Device not responding or not present
403
continue
404
except Exception as e:
405
# Other errors (might be non-SCPI device)
406
found_devices.append({
407
'address': address,
408
'resource': resource_name,
409
'id': f'Present but non-SCPI: {e}'
410
})
411
412
rm.close()
413
return found_devices
414
415
# Scan for devices
416
print("Scanning GPIB bus...")
417
devices = scan_gpib_bus()
418
419
for device in devices:
420
print(f"Address {device['address']}: {device['id']}")
421
```
422
423
### Secondary Addressing
424
425
```python
426
# Some GPIB devices support secondary addressing
427
# Resource format: GPIB[board]::primary::secondary::INSTR
428
429
try:
430
# Open device with secondary address
431
inst = rm.open_resource("GPIB0::5::2::INSTR")
432
433
# Communication works normally
434
idn = inst.query("*IDN?")
435
print(f"Device 5.2: {idn.strip()}")
436
437
except pyvisa.VisaIOError as e:
438
print(f"Secondary addressing error: {e}")
439
finally:
440
inst.close()
441
```
442
443
## Resource String Format
444
445
GPIB resource strings follow the VISA standard:
446
447
```
448
GPIB[board]::primary_address[::secondary_address]::INSTR
449
GPIB[board]::INTFC
450
```
451
452
**Components:**
453
- **board**: GPIB interface board number (usually 0)
454
- **primary_address**: GPIB primary address (1-30)
455
- **secondary_address**: GPIB secondary address (0-30, optional)
456
- **INSTR**: Instrument resource class
457
- **INTFC**: Interface controller resource class
458
459
**Examples:**
460
- `GPIB0::10::INSTR` - Device at primary address 10
461
- `GPIB0::5::2::INSTR` - Device at primary 5, secondary 2
462
- `GPIB1::15::INSTR` - Device on second GPIB board
463
- `GPIB0::INTFC` - GPIB interface controller
464
465
## Error Handling
466
467
GPIB-specific error handling and troubleshooting:
468
469
```python
470
from pyvisa import VisaIOError
471
from pyvisa.constants import StatusCode
472
473
try:
474
inst = rm.open_resource("GPIB0::10::INSTR")
475
except VisaIOError as e:
476
if e.error_code == StatusCode.error_resource_not_found:
477
print("GPIB device not found - check address and connections")
478
elif e.error_code == StatusCode.error_resource_busy:
479
print("GPIB device busy - another application may be using it")
480
elif e.error_code == StatusCode.error_system_error:
481
print("GPIB system error - check interface card and drivers")
482
else:
483
print(f"GPIB open error: {e}")
484
485
# Handle communication timeouts
486
try:
487
response = inst.query("*IDN?", timeout=2000)
488
except VisaIOError as e:
489
if e.error_code == StatusCode.error_timeout:
490
print("GPIB timeout - device may not respond or be misconfigured")
491
elif e.error_code == StatusCode.error_io:
492
print("GPIB I/O error - check bus termination and cables")
493
```
494
495
## Dependencies
496
497
GPIB communication requires platform-specific GPIB drivers:
498
499
### Linux
500
```bash
501
# Install linux-gpib support
502
pip install pyvisa-py[gpib-ctypes]
503
504
# Or use gpib-ctypes directly
505
pip install gpib-ctypes>=0.3.0
506
```
507
508
### Windows
509
```bash
510
# Install gpib-ctypes for Windows
511
pip install pyvisa-py[gpib-ctypes]
512
pip install gpib-ctypes>=0.3.0
513
```
514
515
**Driver Requirements:**
516
- **Linux**: linux-gpib drivers and libraries
517
- **Windows**: National Instruments GPIB drivers or Keysight Connection Expert
518
- **Hardware**: GPIB interface card (PCIe, USB-to-GPIB, Ethernet-to-GPIB)
519
520
## GPIB Hardware
521
522
### Interface Cards
523
- **PCIe GPIB cards**: High-performance, lowest latency
524
- **USB-to-GPIB adapters**: Portable, moderate performance
525
- **Ethernet-to-GPIB**: Remote access, network-based
526
527
### Cable and Termination
528
- Use proper GPIB cables (IEEE 488 standard)
529
- Maximum cable length: 20 meters total, 2 meters between devices
530
- Proper bus termination required (usually automatic)
531
- Star topology not recommended - use linear daisy-chain
532
533
### Bus Configuration
534
- Maximum 15 devices per bus (including controller)
535
- Each device needs unique primary address (1-30)
536
- Controller typically uses address 0
537
- Secondary addressing extends to 960 possible addresses