PySide6.QtSerialPort.QSerialPort

class QSerialPort

Provides functions to access serial ports. More

Inheritance diagram of PySide6.QtSerialPort.QSerialPort

Synopsis

Properties

Methods

Signals

Note

This documentation may contain snippets that were automatically translated from C++ to Python. We always welcome contributions to the snippet translation. If you see an issue with the translation, you can also let us know by creating a ticket on https:/bugreports.qt.io/projects/PYSIDE

Detailed Description

You can get information about the available serial ports using the QSerialPortInfo helper class, which allows an enumeration of all the serial ports in the system. This is useful to obtain the correct name of the serial port you want to use. You can pass an object of the helper class as an argument to the setPort() or setPortName() methods to assign the desired serial device.

After setting the port, you can open it in read-only (r/o), write-only (w/o), or read-write (r/w) mode using the open() method.

Note

The serial port is always opened with exclusive access (that is, no other process or thread can access an already opened serial port).

Use the close() method to close the port and cancel the I/O operations.

Having successfully opened, QSerialPort tries to determine the current configuration of the port and initializes itself. You can reconfigure the port to the desired setting using the setBaudRate() , setDataBits() , setParity() , setStopBits() , and setFlowControl() methods.

There are a couple of properties to work with the pinout signals namely: dataTerminalReady , requestToSend . It is also possible to use the pinoutSignals() method to query the current pinout signals set.

Once you know that the ports are ready to read or write, you can use the read() or write() methods. Alternatively the readLine() and readAll() convenience methods can also be invoked. If not all the data is read at once, the remaining data will be available for later as new incoming data is appended to the QSerialPort ‘s internal read buffer. You can limit the size of the read buffer using setReadBufferSize() .

QSerialPort provides a set of functions that suspend the calling thread until certain signals are emitted. These functions can be used to implement blocking serial ports:

  • waitForReadyRead() blocks calls until new data is available for reading.

  • waitForBytesWritten() blocks calls until one payload of data has been written to the serial port.

See the following example:

int numRead = 0, numReadTotal = 0;
char buffer[50];

for (;;) {
    numRead  = serial.read(buffer, 50);

    // Do whatever with the array

    numReadTotal += numRead;
    if (numRead == 0 && !serial.waitForReadyRead())
        break;
}

If waitForReadyRead() returns false, the connection has been closed or an error has occurred.

If an error occurs at any point in time, QSerialPort will emit the errorOccurred() signal. You can also call error() to find the type of error that occurred last.

Programming with a blocking serial port is radically different from programming with a non-blocking serial port. A blocking serial port does not require an event loop and typically leads to simpler code. However, in a GUI application, blocking serial port should only be used in non-GUI threads, to avoid freezing the user interface.

For more details about these approaches, refer to the example applications.

The QSerialPort class can also be used with QTextStream and QDataStream’s stream operators (operator<<() and operator>>()). There is one issue to be aware of, though: make sure that enough data is available before attempting to read by using the operator>>() overloaded operator.

See also

QSerialPortInfo

class Direction

(inherits enum.Flag) This enum describes the possible directions of the data transmission.

Note

This enumeration is used for setting the baud rate of the device separately for each direction on some operating systems (for example, POSIX-like).

Constant

Description

QSerialPort.Input

Input direction.

QSerialPort.Output

Output direction.

QSerialPort.AllDirections

Simultaneously in two directions.

class BaudRate

(inherits enum.IntEnum) This enum describes the baud rate which the communication device operates with.

Note

Only the most common standard baud rates are listed in this enum.

Constant

Description

QSerialPort.Baud1200

1200 baud.

QSerialPort.Baud2400

2400 baud.

QSerialPort.Baud4800

4800 baud.

QSerialPort.Baud9600

9600 baud.

QSerialPort.Baud19200

19200 baud.

QSerialPort.Baud38400

38400 baud.

QSerialPort.Baud57600

57600 baud.

QSerialPort.Baud115200

115200 baud.

See also

baudRate

class DataBits

This enum describes the number of data bits used.

Constant

Description

QSerialPort.Data5

The number of data bits in each character is 5. It is used for Baudot code. It generally only makes sense with older equipment such as teleprinters.

QSerialPort.Data6

The number of data bits in each character is 6. It is rarely used.

QSerialPort.Data7

The number of data bits in each character is 7. It is used for true ASCII. It generally only makes sense with older equipment such as teleprinters.

QSerialPort.Data8

The number of data bits in each character is 8. It is used for most kinds of data, as this size matches the size of a byte. It is almost universally used in newer applications.

See also

dataBits

class Parity

This enum describes the parity scheme used.

Constant

Description

QSerialPort.NoParity

No parity bit it sent. This is the most common parity setting. Error detection is handled by the communication protocol.

QSerialPort.EvenParity

The number of 1 bits in each character, including the parity bit, is always even.

QSerialPort.OddParity

The number of 1 bits in each character, including the parity bit, is always odd. It ensures that at least one state transition occurs in each character.

QSerialPort.SpaceParity

Space parity. The parity bit is sent in the space signal condition. It does not provide error detection information.

QSerialPort.MarkParity

Mark parity. The parity bit is always set to the mark signal condition (logical 1). It does not provide error detection information.

See also

parity

class StopBits

This enum describes the number of stop bits used.

Constant

Description

QSerialPort.OneStop

1 stop bit.

QSerialPort.OneAndHalfStop

1.5 stop bits. This is only for the Windows platform.

QSerialPort.TwoStop

2 stop bits.

See also

stopBits

class FlowControl

This enum describes the flow control used.

Constant

Description

QSerialPort.NoFlowControl

No flow control.

QSerialPort.HardwareControl

Hardware flow control (RTS/CTS).

QSerialPort.SoftwareControl

Software flow control (XON/XOFF).

See also

flowControl

class PinoutSignal

(inherits enum.Flag) This enum describes the possible RS-232 pinout signals.

Constant

Description

QSerialPort.NoSignal

No line active

QSerialPort.DataTerminalReadySignal

DTR (Data Terminal Ready).

QSerialPort.DataCarrierDetectSignal

DCD (Data Carrier Detect).

QSerialPort.DataSetReadySignal

DSR (Data Set Ready).

QSerialPort.RingIndicatorSignal

RNG (Ring Indicator).

QSerialPort.RequestToSendSignal

RTS (Request To Send).

QSerialPort.ClearToSendSignal

CTS (Clear To Send).

QSerialPort.SecondaryTransmittedDataSignal

STD (Secondary Transmitted Data).

QSerialPort.SecondaryReceivedDataSignal

SRD (Secondary Received Data).

See also

pinoutSignals() dataTerminalReady requestToSend

class SerialPortError

This enum describes the errors that may be contained by the error property.

Constant

Description

QSerialPort.NoError

No error occurred.

QSerialPort.DeviceNotFoundError

An error occurred while attempting to open an non-existing device.

QSerialPort.PermissionError

An error occurred while attempting to open an already opened device by another process or a user not having enough permission and credentials to open.

QSerialPort.OpenError

An error occurred while attempting to open an already opened device in this object.

QSerialPort.NotOpenError

This error occurs when an operation is executed that can only be successfully performed if the device is open. This value was introduced in QtSerialPort 5.2.

QSerialPort.WriteError

An I/O error occurred while writing the data.

QSerialPort.ReadError

An I/O error occurred while reading the data.

QSerialPort.ResourceError

An I/O error occurred when a resource becomes unavailable, e.g. when the device is unexpectedly removed from the system.

QSerialPort.UnsupportedOperationError

The requested device operation is not supported or prohibited by the running operating system.

QSerialPort.TimeoutError

A timeout error occurred. This value was introduced in QtSerialPort 5.2.

QSerialPort.UnknownError

An unidentified error occurred.

See also

error

Note

Properties can be used directly when from __feature__ import true_property is used or via accessor functions otherwise.

property baudRateᅟ: int

This property holds the data baud rate for the desired direction.

If the setting is successful or set before opening the port, returns true; otherwise returns false and sets an error code which can be obtained by accessing the value of the error property. To set the baud rate, use the enumeration BaudRate or any positive qint32 value.

Note

If the setting is set before opening the port, the actual serial port setting is done automatically in the open() method right after that the opening of the port succeeds.

Warning

Setting the AllDirections flag is supported on all platforms. Windows supports only this mode.

Warning

Returns equal baud rate in any direction on Windows.

The default value is Baud9600, i.e. 9600 bits per second.

Access functions:
property breakEnabledᅟ: bool

This property holds the state of the transmission line in break.

Returns true on success, false otherwise. If the flag is true then the transmission line is in break state; otherwise is in non-break state.

Note

The serial port has to be open before trying to set or get this property; otherwise returns false and sets the NotOpenError error code. This is a bit unusual as opposed to the regular Qt property settings of a class. However, this is a special use case since the property is set through the interaction with the kernel and hardware. Hence, the two scenarios cannot be completely compared to each other.

Access functions:
property dataBitsᅟ: QSerialPort.DataBits

This property holds the data bits in a frame.

If the setting is successful or set before opening the port, returns true; otherwise returns false and sets an error code which can be obtained by accessing the value of the error property.

Note

If the setting is set before opening the port, the actual serial port setting is done automatically in the open() method right after that the opening of the port succeeds.

The default value is Data8, i.e. 8 data bits.

Access functions:
property dataTerminalReadyᅟ: bool

This property holds the state (high or low) of the line signal DTR.

Returns true on success, false otherwise. If the flag is true then the DTR signal is set to high; otherwise low.

Note

The serial port has to be open before trying to set or get this property; otherwise false is returned and the error code is set to NotOpenError .

See also

pinoutSignals()

Access functions:
property errorᅟ: QSerialPort.SerialPortError

This property holds the error status of the serial port.

The I/O device status returns an error code. For example, if open() returns false, or a read/write operation returns -1, this property can be used to figure out the reason why the operation failed.

The error code is set to the default NoError after a call to clearError()

Access functions:
property flowControlᅟ: QSerialPort.FlowControl

This property holds the desired flow control mode.

If the setting is successful or set before opening the port, returns true; otherwise returns false and sets an error code which can be obtained by accessing the value of the error property.

Note

If the setting is set before opening the port, the actual serial port setting is done automatically in the open() method right after that the opening of the port succeeds.

The default value is NoFlowControl , i.e. no flow control.

Access functions:
property parityᅟ: QSerialPort.Parity

This property holds the parity checking mode.

If the setting is successful or set before opening the port, returns true; otherwise returns false and sets an error code which can be obtained by accessing the value of the error property.

Note

If the setting is set before opening the port, the actual serial port setting is done automatically in the open() method right after that the opening of the port succeeds.

The default value is NoParity , i.e. no parity.

Access functions:
property requestToSendᅟ: bool

This property holds the state (high or low) of the line signal RTS.

Returns true on success, false otherwise. If the flag is true then the RTS signal is set to high; otherwise low.

Note

The serial port has to be open before trying to set or get this property; otherwise false is returned and the error code is set to NotOpenError .

Note

An attempt to control the RTS signal in the HardwareControl mode will fail with error code set to UnsupportedOperationError , because the signal is automatically controlled by the driver.

See also

pinoutSignals()

Access functions:
property stopBitsᅟ: QSerialPort.StopBits

This property holds the number of stop bits in a frame.

If the setting is successful or set before opening the port, returns true; otherwise returns false and sets an error code which can be obtained by accessing the value of the error property.

Note

If the setting is set before opening the port, the actual serial port setting is done automatically in the open() method right after that the opening of the port succeeds.

The default value is OneStop , i.e. 1 stop bit.

Access functions:
__init__([parent=None])
Parameters:

parentQObject

Constructs a new serial port object with the given parent.

__init__(info[, parent=None])
Parameters:

Constructs a new serial port object with the given parent to represent the serial port with the specified helper class serialPortInfo.

__init__(name[, parent=None])
Parameters:

Constructs a new serial port object with the given parent to represent the serial port with the specified name.

The name should have a specific format; see the setPort() method.

baudRate([directions=QSerialPort.Direction.AllDirections])
Parameters:

directions – Combination of Direction

Return type:

int

See also

setBaudRate()

baudRateChanged(baudRate, directions)
Parameters:
  • baudRate – int

  • directions – Combination of Direction

This signal is emitted after the baud rate has been changed. The new baud rate is passed as baudRate and directions as directions.

See also

baudRate

Notification signal of property baudRateᅟ .

breakEnabledChanged(set)
Parameters:

set – bool

Notification signal of property breakEnabledᅟ .

clear([directions=QSerialPort.Direction.AllDirections])
Parameters:

directions – Combination of Direction

Return type:

bool

Discards all characters from the output or input buffer, depending on given directions directions. This includes clearing the internal class buffers and the UART (driver) buffers. Also terminate pending read or write operations. If successful, returns true; otherwise returns false.

Note

The serial port has to be open before trying to clear any buffered data; otherwise returns false and sets the NotOpenError error code.

clearError()

Reset function of property errorᅟ .

dataBits()
Return type:

DataBits

See also

setDataBits()

Getter of property dataBitsᅟ .

dataBitsChanged(dataBits)
Parameters:

dataBitsDataBits

This signal is emitted after the data bits in a frame has been changed. The new data bits in a frame is passed as dataBits.

See also

dataBits

Notification signal of property dataBitsᅟ .

dataTerminalReadyChanged(set)
Parameters:

set – bool

This signal is emitted after the state (high or low) of the line signal DTR has been changed. The new the state (high or low) of the line signal DTR is passed as set.

See also

dataTerminalReady

Notification signal of property dataTerminalReadyᅟ .

error()
Return type:

SerialPortError

Getter of property errorᅟ .

errorOccurred(error)
Parameters:

errorSerialPortError

This signal is emitted when an error occurs in the serial port. The specified error describes the type of error that occurred.

See also

error

Notification signal of property errorᅟ .

flowControl()
Return type:

FlowControl

See also

setFlowControl()

Getter of property flowControlᅟ .

flowControlChanged(flowControl)
Parameters:

flowControlFlowControl

This signal is emitted after the flow control mode has been changed. The new flow control mode is passed as flow.

See also

flowControl

Notification signal of property flowControlᅟ .

flush()
Return type:

bool

This function writes as much as possible from the internal write buffer to the underlying serial port without blocking. If any data was written, this function returns true; otherwise returns false.

Call this function for sending the buffered data immediately to the serial port. The number of bytes successfully written depends on the operating system. In most cases, this function does not need to be called, because the QSerialPort class will start sending data automatically once control is returned to the event loop. In the absence of an event loop, call waitForBytesWritten() instead.

Note

The serial port has to be open before trying to flush any buffered data; otherwise returns false and sets the NotOpenError error code.

See also

waitForBytesWritten()

handle()
Return type:

int

If the platform is supported and the serial port is open, returns the native serial port handle; otherwise returns -1.

Warning

This function is for expert use only; use it at your own risk. Furthermore, this function carries no compatibility promise between minor Qt releases.

isBreakEnabled()
Return type:

bool

Getter of property breakEnabledᅟ .

isDataTerminalReady()
Return type:

bool

Getter of property dataTerminalReadyᅟ .

isRequestToSend()
Return type:

bool

Getter of property requestToSendᅟ .

parity()
Return type:

Parity

See also

setParity()

Getter of property parityᅟ .

parityChanged(parity)
Parameters:

parityParity

This signal is emitted after the parity checking mode has been changed. The new parity checking mode is passed as parity.

See also

parity

Notification signal of property parityᅟ .

pinoutSignals()
Return type:

Combination of PinoutSignal

Returns the state of the line signals in a bitmap format.

From this result, it is possible to allocate the state of the desired signal by applying a mask “AND”, where the mask is the desired enumeration value from PinoutSignals .

Note

This method performs a system call, thus ensuring that the line signal states are returned properly. This is necessary when the underlying operating systems cannot provide proper notifications about the changes.

Note

The serial port has to be open before trying to get the pinout signals; otherwise returns NoSignal and sets the NotOpenError error code.

See also

dataTerminalReady requestToSend

portName()
Return type:

str

Returns the name set by setPort() or passed to the QSerialPort constructor. This name is short, i.e. it is extracted and converted from the internal variable system location of the device. The conversion algorithm is platform specific:

Platform

Brief Description

Windows

Removes the prefix “\\.\” or “//./” from the system location and returns the remainder of the string.

Unix, BSD

Removes the prefix “/dev/” from the system location and returns the remainder of the string.

readBufferSize()
Return type:

int

Returns the size of the internal read buffer. This limits the amount of data that the client can receive before calling the read() or readAll() methods.

A read buffer size of 0 (the default) means that the buffer has no size limit, ensuring that no data is lost.

requestToSendChanged(set)
Parameters:

set – bool

This signal is emitted after the state (high or low) of the line signal RTS has been changed. The new the state (high or low) of the line signal RTS is passed as set.

See also

requestToSend

Notification signal of property requestToSendᅟ .

setBaudRate(baudRate[, directions=QSerialPort.Direction.AllDirections])
Parameters:
  • baudRate – int

  • directions – Combination of Direction

Return type:

bool

See also

baudRate()

setBreakEnabled([set=true])
Parameters:

set – bool

Return type:

bool

See also

isBreakEnabled()

setDataBits(dataBits)
Parameters:

dataBitsDataBits

Return type:

bool

See also

dataBits()

setDataTerminalReady(set)
Parameters:

set – bool

Return type:

bool

setFlowControl(flowControl)
Parameters:

flowControlFlowControl

Return type:

bool

See also

flowControl()

setParity(parity)
Parameters:

parityParity

Return type:

bool

See also

parity()

setPort(info)
Parameters:

infoQSerialPortInfo

Sets the port stored in the serial port info instance serialPortInfo.

setPortName(name)
Parameters:

name – str

Sets the name of the serial port.

The name of the serial port can be passed as either a short name or the long system location if necessary.

setReadBufferSize(size)
Parameters:

size – int

Sets the size of QSerialPort ‘s internal read buffer to be size bytes.

If the buffer size is limited to a certain size, QSerialPort will not buffer more than this size of data. The special case of a buffer size of 0 means that the read buffer is unlimited and all incoming data is buffered. This is the default.

This option is useful if the data is only read at certain points in time (for instance in a real-time streaming application) or if the serial port should be protected against receiving too much data, which may eventually cause the application to run out of memory.

setRequestToSend(set)
Parameters:

set – bool

Return type:

bool

setStopBits(stopBits)
Parameters:

stopBitsStopBits

Return type:

bool

See also

stopBits()

stopBits()
Return type:

StopBits

See also

setStopBits()

Getter of property stopBitsᅟ .

stopBitsChanged(stopBits)
Parameters:

stopBitsStopBits

This signal is emitted after the number of stop bits in a frame has been changed. The new number of stop bits in a frame is passed as stopBits.

See also

stopBits

Notification signal of property stopBitsᅟ .