QSerialPort Class

Provides functions to access serial ports. More...

Header: #include <QSerialPort>
qmake: QT += serialport
Since: Qt 5.1
Inherits: QIODevice

This class was introduced in Qt 5.1.

Note: All functions in this class are reentrant.

Public Types

enum BaudRate { Baud1200, Baud2400, Baud4800, Baud9600, Baud19200, …, UnknownBaud }
enum DataBits { Data5, Data6, Data7, Data8, UnknownDataBits }
enum Direction { Input, Output, AllDirections }
enum FlowControl { NoFlowControl, HardwareControl, SoftwareControl, UnknownFlowControl }
enum Parity { NoParity, EvenParity, OddParity, SpaceParity, MarkParity, UnknownParity }
enum PinoutSignal { NoSignal, TransmittedDataSignal, ReceivedDataSignal, DataTerminalReadySignal, DataCarrierDetectSignal, …, SecondaryReceivedDataSignal }
enum SerialPortError { NoError, DeviceNotFoundError, PermissionError, OpenError, NotOpenError, …, UnknownError }
enum StopBits { OneStop, OneAndHalfStop, TwoStop, UnknownStopBits }

Properties

Public Functions

qint32 baudRate(QSerialPort::Directions directions = AllDirections) const
void clearError()
QSerialPort::DataBits dataBits() const
QSerialPort::SerialPortError error() const
QSerialPort::FlowControl flowControl() const
bool isBreakEnabled() const
bool isDataTerminalReady()
bool isRequestToSend()
QSerialPort::Parity parity() const
bool setBaudRate(qint32 baudRate, QSerialPort::Directions directions = AllDirections)
bool setBreakEnabled(bool set = true)
bool setDataBits(QSerialPort::DataBits dataBits)
bool setDataTerminalReady(bool set)
bool setFlowControl(QSerialPort::FlowControl flowControl)
bool setParity(QSerialPort::Parity parity)
bool setRequestToSend(bool set)
bool setStopBits(QSerialPort::StopBits stopBits)
QSerialPort::StopBits stopBits() const

Signals

void baudRateChanged(qint32 baudRate, QSerialPort::Directions directions)
void breakEnabledChanged(bool set)
void dataBitsChanged(QSerialPort::DataBits dataBits)
void dataTerminalReadyChanged(bool set)
void error(QSerialPort::SerialPortError serialPortError)
void flowControlChanged(QSerialPort::FlowControl flowControl)
void parityChanged(QSerialPort::Parity parity)
void requestToSendChanged(bool set)
void stopBitsChanged(QSerialPort::StopBits stopBits)

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: QSerialPort::dataTerminalReady, QSerialPort::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.

Note: Not all error conditions are handled in a platform independent way in QSerialport, as for example the Framing, Parity, and Break condition errors. These kind of errors need to be handled by the application code, probably using OS system specific ioctls on the device descriptor and/or parsing the stream's byte-stuffing.

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.

Member Type Documentation

enum QSerialPort::BaudRate

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.

ConstantValueDescription
QSerialPort::Baud120012001200 baud.
QSerialPort::Baud240024002400 baud.
QSerialPort::Baud480048004800 baud.
QSerialPort::Baud960096009600 baud.
QSerialPort::Baud192001920019200 baud.
QSerialPort::Baud384003840038400 baud.
QSerialPort::Baud576005760057600 baud.
QSerialPort::Baud115200115200115200 baud.
QSerialPort::UnknownBaud-1Unknown baud. This value is obsolete. It is provided to keep old source code working. We strongly advise against using it in new code.

See also QSerialPort::baudRate.

enum QSerialPort::DataBits

This enum describes the number of data bits used.

ConstantValueDescription
QSerialPort::Data55The 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::Data66The number of data bits in each character is 6. It is rarely used.
QSerialPort::Data77The 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::Data88The 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.
QSerialPort::UnknownDataBits-1Unknown number of bits. This value is obsolete. It is provided to keep old source code working. We strongly advise against using it in new code.

See also QSerialPort::dataBits.

enum QSerialPort::Direction

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).

ConstantValueDescription
QSerialPort::Input1Input direction.
QSerialPort::Output2Output direction.
QSerialPort::AllDirectionsInput | OutputSimultaneously in two directions.

enum QSerialPort::FlowControl

This enum describes the flow control used.

ConstantValueDescription
QSerialPort::NoFlowControl0No flow control.
QSerialPort::HardwareControl1Hardware flow control (RTS/CTS).
QSerialPort::SoftwareControl2Software flow control (XON/XOFF).
QSerialPort::UnknownFlowControl-1Unknown flow control. This value is obsolete. It is provided to keep old source code working. We strongly advise against using it in new code.

See also QSerialPort::flowControl.

enum QSerialPort::Parity

This enum describes the parity scheme used.

ConstantValueDescription
QSerialPort::NoParity0No parity bit it sent. This is the most common parity setting. Error detection is handled by the communication protocol.
QSerialPort::EvenParity2The number of 1 bits in each character, including the parity bit, is always even.
QSerialPort::OddParity3The 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::SpaceParity4Space parity. The parity bit is sent in the space signal condition. It does not provide error detection information.
QSerialPort::MarkParity5Mark parity. The parity bit is always set to the mark signal condition (logical 1). It does not provide error detection information.
QSerialPort::UnknownParity-1Unknown parity. This value is obsolete. It is provided to keep old source code working. We strongly advise against using it in new code.

See also QSerialPort::parity.

enum QSerialPort::PinoutSignal

This enum describes the possible RS-232 pinout signals.

ConstantValueDescription
QSerialPort::NoSignal0x00No line active
QSerialPort::TransmittedDataSignal0x01TxD (Transmitted Data). This value is obsolete. It is provided to keep old source code working. We strongly advise against using it in new code.
QSerialPort::ReceivedDataSignal0x02RxD (Received Data). This value is obsolete. It is provided to keep old source code working. We strongly advise against using it in new code.
QSerialPort::DataTerminalReadySignal0x04DTR (Data Terminal Ready).
QSerialPort::DataCarrierDetectSignal0x08DCD (Data Carrier Detect).
QSerialPort::DataSetReadySignal0x10DSR (Data Set Ready).
QSerialPort::RingIndicatorSignal0x20RNG (Ring Indicator).
QSerialPort::RequestToSendSignal0x40RTS (Request To Send).
QSerialPort::ClearToSendSignal0x80CTS (Clear To Send).
QSerialPort::SecondaryTransmittedDataSignal0x100STD (Secondary Transmitted Data).
QSerialPort::SecondaryReceivedDataSignal0x200SRD (Secondary Received Data).

See also pinoutSignals(), QSerialPort::dataTerminalReady, and QSerialPort::requestToSend.

enum QSerialPort::SerialPortError

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

ConstantValueDescription
QSerialPort::NoError0No error occurred.
QSerialPort::DeviceNotFoundError1An error occurred while attempting to open an non-existing device.
QSerialPort::PermissionError2An 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::OpenError3An error occurred while attempting to open an already opened device in this object.
QSerialPort::NotOpenError13This 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::ParityError4Parity error detected by the hardware while reading data. This value is obsolete. We strongly advise against using it in new code.
QSerialPort::FramingError5Framing error detected by the hardware while reading data. This value is obsolete. We strongly advise against using it in new code.
QSerialPort::BreakConditionError6Break condition detected by the hardware on the input line. This value is obsolete. We strongly advise against using it in new code.
QSerialPort::WriteError7An I/O error occurred while writing the data.
QSerialPort::ReadError8An I/O error occurred while reading the data.
QSerialPort::ResourceError9An I/O error occurred when a resource becomes unavailable, e.g. when the device is unexpectedly removed from the system.
QSerialPort::UnsupportedOperationError10The requested device operation is not supported or prohibited by the running operating system.
QSerialPort::TimeoutError12A timeout error occurred. This value was introduced in QtSerialPort 5.2.
QSerialPort::UnknownError11An unidentified error occurred.

See also QSerialPort::error.

enum QSerialPort::StopBits

This enum describes the number of stop bits used.

ConstantValueDescription
QSerialPort::OneStop11 stop bit.
QSerialPort::OneAndHalfStop31.5 stop bits. This is only for the Windows platform.
QSerialPort::TwoStop22 stop bits.
QSerialPort::UnknownStopBits-1Unknown number of stop bits. This value is obsolete. It is provided to keep old source code working. We strongly advise against using it in new code.

See also QSerialPort::stopBits.

Property Documentation

baudRate : qint32

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 QSerialPort::error property. To set the baud rate, use the enumeration QSerialPort::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 QSerialPort::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:

qint32 baudRate(QSerialPort::Directions directions = AllDirections) const
bool setBaudRate(qint32 baudRate, QSerialPort::Directions directions = AllDirections)

Notifier signal:

void baudRateChanged(qint32 baudRate, QSerialPort::Directions directions)

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.

This property was introduced in Qt 5.5.

Access functions:

bool isBreakEnabled() const
bool setBreakEnabled(bool set = true)

Notifier signal:

void breakEnabledChanged(bool set)

dataBits : 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 QSerialPort::error property.

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

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

Access functions:

QSerialPort::DataBits dataBits() const
bool setDataBits(QSerialPort::DataBits dataBits)

Notifier signal:

void dataBitsChanged(QSerialPort::DataBits dataBits)

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.

Access functions:

bool isDataTerminalReady()
bool setDataTerminalReady(bool set)

Notifier signal:

void dataTerminalReadyChanged(bool set)

See also pinoutSignals().

error : 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 QSerialPort::NoError after a call to clearError()

Access functions:

QSerialPort::SerialPortError error() const
void error(QSerialPort::SerialPortError serialPortError)
void clearError()

flowControl : 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 QSerialPort::error property.

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

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

Access functions:

QSerialPort::FlowControl flowControl() const
bool setFlowControl(QSerialPort::FlowControl flowControl)

Notifier signal:

void flowControlChanged(QSerialPort::FlowControl flowControl)

parity : 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 QSerialPort::error property.

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

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

Access functions:

QSerialPort::Parity parity() const
bool setParity(QSerialPort::Parity parity)

Notifier signal:

void parityChanged(QSerialPort::Parity parity)

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.

Access functions:

bool isRequestToSend()
bool setRequestToSend(bool set)

Notifier signal:

void requestToSendChanged(bool set)

See also pinoutSignals().

stopBits : 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 QSerialPort::error property.

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

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

Access functions:

QSerialPort::StopBits stopBits() const
bool setStopBits(QSerialPort::StopBits stopBits)

Notifier signal:

void stopBitsChanged(QSerialPort::StopBits stopBits)