2.19 USB Serial
Module API Manual#
Overview#
The USB Serial module provides functionality for data communication via USB serial ports. This module implements the standard stream protocol interface and supports read/write operations.
This module supports communication with 4G modules via AT commands.
Constructor#
usb_serial(path="/dev/ttyUSB1", timeout_ms=300)
#
Creates a USB Serial object.
Parameters:
path
(str): Serial device path, defaults to “/dev/ttyUSB1”timeout_ms
(int): Read/write timeout in milliseconds, defaults to 300ms
Returns: USB Serial object
Example:
import usb_serial
# Create USB Serial object
serial = usb_serial.usb_serial("/dev/ttyUSB1", timeout_ms=300)
Methods#
open([path])
#
Opens the USB serial device.
Parameters:
path
(str, optional): If provided, will use this path instead of the one specified in the constructor
Returns:
True
: Open successfulFalse
: Open failed
Example:
serial.open() # Use path specified in constructor
serial.open("/dev/ttyUSB2") # Use new path
close()
#
Closes the USB serial device.
Example:
serial.close()
read(size)
#
Reads data from the serial port.
Parameters:
size
(int): Number of bytes to read
Returns: Read data (bytes type)
readinto(buf)
#
Reads data into a buffer.
Parameters:
buf
(bytearray): Target buffer
Returns: Number of bytes actually read
readline()
#
Reads a line of data until encountering a newline character or timeout.
Returns: Line data read (bytes type)
write(buf)
#
Writes data to the serial port.
Parameters:
buf
(bytes/bytearray): Data to write
Returns: Number of bytes actually written
Properties#
path
#
Gets or sets the serial device path.
Example:
print(serial.path) # Get current path
serial.path = "/dev/ttyUSB1" # Set new path
timeout_ms
#
Gets or sets the read/write timeout (milliseconds).
Example:
print(serial.timeout_ms) # Get current timeout
serial.timeout_ms = 1000 # Set timeout to 1 second
Stream Protocol Support#
The USB Serial object implements the standard stream protocol and can be directly used in contexts requiring stream objects.
Example:
# Read a line of data using readline()
line = serial.readline()
# Write data using write()
serial.write(b"Hello World\n")
Notes#
The
close()
method is automatically called when the object is destroyedAll read/write operations are controlled by the
timeout_ms
parameterCalling read/write methods when the serial port is not open will raise an OSError exception
The default device path is “/dev/ttyUSB1” - please modify according to actual device