0
# Serial Communication
1
2
Serial communication support for interfacing with instruments via serial ports, USB-to-serial adapters, and virtual COM ports. The SerialSession class provides comprehensive serial communication capabilities with configurable parameters and robust error handling.
3
4
## Capabilities
5
6
### SerialSession Class
7
8
Handles serial communication with instruments using PySerial as the underlying library, supporting various serial configurations and termination modes.
9
10
```python { .api }
11
class SerialSession:
12
"""Session for serial port communication."""
13
14
def __init__(self, resource_manager_session, resource_name, parsed, open_timeout):
15
"""
16
Initialize serial session.
17
18
Args:
19
resource_manager_session (VISARMSession): Parent RM session
20
resource_name (str): Serial resource name (e.g., "ASRL1::INSTR")
21
parsed (rname.ResourceName): Parsed resource name
22
open_timeout (int): Connection timeout in milliseconds
23
"""
24
25
def read(self, count):
26
"""
27
Read data from serial port.
28
29
Args:
30
count (int): Maximum number of bytes to read
31
32
Returns:
33
Tuple[bytes, StatusCode]: Data read and operation status
34
"""
35
36
def write(self, data):
37
"""
38
Write data to serial port.
39
40
Args:
41
data (bytes): Data to transmit
42
43
Returns:
44
Tuple[int, StatusCode]: Number of bytes written and status
45
"""
46
47
def flush(self, mask):
48
"""
49
Flush serial port buffers.
50
51
Args:
52
mask (constants.BufferOperation): Buffer flush operation type
53
54
Returns:
55
StatusCode: Operation result
56
"""
57
58
def close(self):
59
"""
60
Close serial port connection.
61
62
Returns:
63
StatusCode: Operation result
64
"""
65
66
@staticmethod
67
def list_resources():
68
"""
69
List available serial ports.
70
71
Returns:
72
List[str]: List of available serial port resource strings
73
"""
74
```
75
76
### Serial Port Configuration
77
78
Configure serial communication parameters through VISA attributes for baud rate, data bits, parity, stop bits, and flow control.
79
80
```python { .api }
81
# Common serial attributes (accessed via get_attribute/set_attribute)
82
VI_ATTR_ASRL_BAUD = 0x3FFF0021 # Baud rate
83
VI_ATTR_ASRL_DATA_BITS = 0x3FFF0022 # Data bits (5-8)
84
VI_ATTR_ASRL_PARITY = 0x3FFF0023 # Parity setting
85
VI_ATTR_ASRL_STOP_BITS = 0x3FFF0024 # Stop bits
86
VI_ATTR_ASRL_FLOW_CNTRL = 0x3FFF0025 # Flow control
87
VI_ATTR_ASRL_END_IN = 0x3FFF00B0 # Input termination method
88
VI_ATTR_ASRL_END_OUT = 0x3FFF00B1 # Output termination method
89
```
90
91
### Termination Handling
92
93
Control how data transmission is terminated and detected for reliable communication with various instrument protocols.
94
95
```python { .api }
96
# Termination constants
97
VI_ASRL_END_NONE = 0 # No termination
98
VI_ASRL_END_LAST_BIT = 1 # Use last bit for termination
99
VI_ASRL_END_TERMCHAR = 2 # Use termination character
100
VI_ASRL_END_BREAK = 3 # Use break condition
101
102
# Parity constants
103
VI_ASRL_PAR_NONE = 0 # No parity
104
VI_ASRL_PAR_ODD = 1 # Odd parity
105
VI_ASRL_PAR_EVEN = 2 # Even parity
106
VI_ASRL_PAR_MARK = 3 # Mark parity
107
VI_ASRL_PAR_SPACE = 4 # Space parity
108
109
# Flow control constants
110
VI_ASRL_FLOW_NONE = 0 # No flow control
111
VI_ASRL_FLOW_XON_XOFF = 1 # Software flow control
112
VI_ASRL_FLOW_RTS_CTS = 2 # Hardware flow control
113
VI_ASRL_FLOW_DTR_DSR = 4 # DTR/DSR flow control
114
```
115
116
## Usage Examples
117
118
### Basic Serial Communication
119
120
```python
121
import pyvisa
122
123
# Use PyVISA-py backend
124
rm = pyvisa.ResourceManager('@py')
125
126
# Open serial instrument
127
# Resource formats:
128
# - Windows: "ASRLCOM1::INSTR"
129
# - Linux: "ASRL/dev/ttyUSB0::INSTR"
130
# - macOS: "ASRL/dev/cu.usbserial::INSTR"
131
132
try:
133
inst = rm.open_resource("ASRL/dev/ttyUSB0::INSTR")
134
135
# Configure serial parameters
136
inst.baud_rate = 9600
137
inst.data_bits = 8
138
inst.parity = pyvisa.constants.Parity.none
139
inst.stop_bits = pyvisa.constants.StopBits.one
140
inst.flow_control = pyvisa.constants.ControlFlow.none
141
142
# Set termination characters
143
inst.read_termination = '\\n'
144
inst.write_termination = '\\n'
145
146
# Set timeout
147
inst.timeout = 2000 # 2 seconds
148
149
# Send commands
150
inst.write("*IDN?")
151
response = inst.read()
152
print("Instrument ID:", response.strip())
153
154
# Query shortcut (write + read)
155
response = inst.query("*IDN?")
156
print("ID:", response.strip())
157
158
finally:
159
inst.close()
160
rm.close()
161
```
162
163
### Advanced Serial Configuration
164
165
```python
166
from pyvisa import constants
167
168
# Open with specific configuration
169
inst = rm.open_resource("ASRL1::INSTR")
170
171
# Set specific serial parameters using attributes
172
inst.set_visa_attribute(constants.VI_ATTR_ASRL_BAUD, 115200)
173
inst.set_visa_attribute(constants.VI_ATTR_ASRL_DATA_BITS, 8)
174
inst.set_visa_attribute(constants.VI_ATTR_ASRL_PARITY, constants.VI_ASRL_PAR_EVEN)
175
inst.set_visa_attribute(constants.VI_ATTR_ASRL_STOP_BITS, constants.VI_ASRL_STOP_TWO)
176
177
# Configure flow control
178
inst.set_visa_attribute(constants.VI_ATTR_ASRL_FLOW_CNTRL, constants.VI_ASRL_FLOW_RTS_CTS)
179
180
# Set termination handling
181
inst.set_visa_attribute(constants.VI_ATTR_ASRL_END_IN, constants.VI_ASRL_END_TERMCHAR)
182
inst.set_visa_attribute(constants.VI_ATTR_ASRL_END_OUT, constants.VI_ASRL_END_TERMCHAR)
183
inst.set_visa_attribute(constants.VI_ATTR_TERMCHAR, ord('\\r'))
184
185
# Query current configuration
186
baud = inst.get_visa_attribute(constants.VI_ATTR_ASRL_BAUD)
187
data_bits = inst.get_visa_attribute(constants.VI_ATTR_ASRL_DATA_BITS)
188
print(f"Config: {baud} baud, {data_bits} data bits")
189
```
190
191
### Binary Data Communication
192
193
```python
194
# Reading binary data
195
inst = rm.open_resource("ASRL1::INSTR")
196
197
# Disable termination for binary data
198
inst.read_termination = None
199
inst.write_termination = None
200
201
# Request specific number of bytes
202
inst.write(b"DATA?")
203
binary_data = inst.read_bytes(1024)
204
print(f"Received {len(binary_data)} bytes")
205
206
# Reading with timeout
207
try:
208
data = inst.read_bytes(512, timeout=1000)
209
except pyvisa.VisaIOError as e:
210
if e.error_code == constants.StatusCode.error_timeout:
211
print("Read timeout occurred")
212
else:
213
raise
214
```
215
216
### Buffer Management
217
218
```python
219
# Flush input/output buffers
220
inst.flush(constants.BufferOperation.discard_read_buffer)
221
inst.flush(constants.BufferOperation.discard_write_buffer)
222
223
# Flush both buffers
224
inst.flush(constants.BufferOperation.discard_read_buffer |
225
constants.BufferOperation.discard_write_buffer)
226
227
# Check bytes available
228
try:
229
# Non-blocking read to check if data is available
230
data = inst.read_bytes(1, timeout=0)
231
print("Data available:", data)
232
except pyvisa.VisaIOError as e:
233
if e.error_code == constants.StatusCode.error_timeout:
234
print("No data available")
235
```
236
237
## Resource Discovery
238
239
Serial port enumeration automatically detects available serial interfaces:
240
241
```python
242
# List all available serial ports
243
rm = pyvisa.ResourceManager('@py')
244
resources = rm.list_resources('ASRL?*::INSTR')
245
print("Serial ports:", resources)
246
247
# Typical resource strings:
248
# Windows: ['ASRLCOM1::INSTR', 'ASRLCOM3::INSTR']
249
# Linux: ['ASRL/dev/ttyUSB0::INSTR', 'ASRL/dev/ttyACM0::INSTR']
250
# macOS: ['ASRL/dev/cu.usbserial-123::INSTR']
251
```
252
253
## Error Handling
254
255
Common serial communication errors and their handling:
256
257
```python
258
from pyvisa import VisaIOError
259
from pyvisa.constants import StatusCode
260
261
try:
262
inst = rm.open_resource("ASRL99::INSTR") # Non-existent port
263
except VisaIOError as e:
264
if e.error_code == StatusCode.error_resource_not_found:
265
print("Serial port not found")
266
elif e.error_code == StatusCode.error_resource_busy:
267
print("Serial port is already in use")
268
else:
269
print(f"Error opening serial port: {e}")
270
271
try:
272
response = inst.query("*IDN?", timeout=1000)
273
except VisaIOError as e:
274
if e.error_code == StatusCode.error_timeout:
275
print("Communication timeout - check connections and settings")
276
elif e.error_code == StatusCode.error_io:
277
print("I/O error - check serial configuration")
278
```
279
280
## Dependencies
281
282
Serial communication requires the optional PySerial package:
283
284
```bash
285
# Install PySerial support
286
pip install pyvisa-py[serial]
287
288
# Or install PySerial directly
289
pip install pyserial>=3.0
290
```
291
292
Without PySerial, serial resources will not be available and attempting to open serial sessions will raise import errors.
293
294
## Platform Considerations
295
296
### Windows
297
- COM port names: `COM1`, `COM2`, etc.
298
- Resource strings: `ASRLCOM1::INSTR`
299
- USB-to-serial adapters automatically assigned COM numbers
300
301
### Linux
302
- Device paths: `/dev/ttyUSB0`, `/dev/ttyACM0`, `/dev/ttyS0`
303
- Resource strings: `ASRL/dev/ttyUSB0::INSTR`
304
- May require udev rules or user permissions for device access
305
306
### macOS
307
- Device paths: `/dev/cu.usbserial-*`, `/dev/cu.SLAB_USBtoUART`
308
- Resource strings: `ASRL/dev/cu.usbserial-123::INSTR`
309
- USB-to-serial adapters appear with vendor-specific names