Contents

SerialPort Class Reference

The SerialPort class provides functions to access serial ports. More...

    #include <SerialPort>

Inherits: QIODevice.

Note: All functions in this class are reentrant.

This class was introduced in SerialPort 5.0.

Public Types

enum DataBits { Data5, Data6, Data7, Data8, UnknownDataBits }
enum DataErrorPolicy { SkipPolicy, PassZeroPolicy, IgnorePolicy, StopReceivingPolicy, UnknownPolicy }
enum Direction { Input, Output, AllDirections }
flags Directions
enum FlowControl { NoFlowControl, HardwareControl, SoftwareControl, UnknownFlowControl }
enum Line { Le, Dtr, Rts, St, ..., Dsr }
flags Lines
enum Parity { EvenParity, OddParity, SpaceParity, MarkParity, UnknownParity }
enum PortError { NoError, NoSuchDeviceError, PermissionDeniedError, DeviceAlreadyOpenedError, ..., UnknownPortError }
enum Rate { Rate1200, Rate2400, Rate4800, Rate9600, ..., UnknownRate }
enum StopBits { OneStop, OneAndHalfStop, TwoStop, UnknownStopBits }

Properties

Public Functions

SerialPort ( QObject * parent = 0 )
SerialPort ( const QString & name, QObject * parent = 0 )
SerialPort ( const SerialPortInfo & info, QObject * parent = 0 )
virtual ~SerialPort ()
bool clear ( Directions dir = AllDirections )
void clearError ()
DataBits dataBits () const
DataErrorPolicy dataErrorPolicy () const
bool dtr () const
PortError error () const
FlowControl flowControl () const
bool flush ()
Lines lines () const
virtual bool open ( OpenMode mode )
Parity parity () const
QString portName () const
qint32 rate ( Directions dir = AllDirections ) const
qint64 readBufferSize () const
bool restoreSettingsOnClose () const
bool rts () const
bool setDataBits ( DataBits dataBits )
bool setDataErrorPolicy ( DataErrorPolicy policy = IgnorePolicy )
bool setFlowControl ( FlowControl flow )
bool setParity ( Parity parity )
void setPort ( const QString & name )
void setPort ( const SerialPortInfo & info )
bool setRate ( qint32 rate, Directions dir = AllDirections )
void setReadBufferSize ( qint64 size )
void setRestoreSettingsOnClose ( bool restore )
bool setStopBits ( StopBits stopBits )
StopBits stopBits () const

Reimplemented Public Functions

virtual bool atEnd () const
virtual qint64 bytesAvailable () const
virtual qint64 bytesToWrite () const
virtual bool canReadLine () const
virtual void close ()
virtual bool isSequential () const
virtual bool waitForBytesWritten ( int msecs )
virtual bool waitForReadyRead ( int msecs )

Public Slots

bool clearBreak ( bool clear = true )
bool sendBreak ( int duration = 0 )
bool setBreak ( bool set = true )
bool setDtr ( bool set )
bool setRts ( bool set )

Signals

void dataBitsChanged ( DataBits dataBits )
void dataErrorPolicyChanged ( DataErrorPolicy policy )
void dtrChanged ( bool set )
void errorChanged ( PortError error )
void flowControlChanged ( FlowControl flow )
void parityChanged ( Parity parity )
void rateChanged ( qint32 rate, Directions dir )
void restoreSettingsOnCloseChanged ( bool restore )
void rtsChanged ( bool set )
void stopBitsChanged ( StopBits stopBits )

Reimplemented Protected Functions

virtual qint64 readData ( char * data, qint64 maxSize )
virtual qint64 readLineData ( char * data, qint64 maxSize )
virtual qint64 writeData ( const char * data, qint64 maxSize )

Additional Inherited Members

Detailed Description

The SerialPort class provides functions to access serial ports.

This class resembles the functionality and behavior of the QAbstractSocket class in many aspects, for instance the I/O operations, the implementation of the wait methods, the internal architecture and so forth. Certain SerialPort method implementations were taken directly from QAbstractSocket with only minor changes.

The features of the implementation and the conduct of the class are listed below:

To get started with the SerialPort class, first create an object of that.

Then, call the setPort() method in order to assign the object with the name of the desired serial port (which has to be present in the system). The name has to follow a certain format, which is platform dependent.

The helper class SerialPortInfo allows the enumeration of all the serial ports in the system. This is useful to obtain the correct serial port name.

The SerialPortInfo class can also be used as an input parameter for the setPort() method (to retrieve the currently assigned name, use the portName() method).

After that, the serial port can be opened 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 (i.e. no other process or thread can access an already opened serial port).

Having successfully opened, the SerialPort determines its current configuration and initializes itself to that. To access the current configuration use the rate(), dataBits(), parity(), stopBits(), and flowControl() methods.

If these settings are satisfying, the I/O operation can be proceed with. Otherwise the port can be reconfigured to the desired setting using the setRate(), setDataBits(), setParity(), setStopBits(), and setFlowControl() methods.

Read or write the data by calling read() or write(). Alternatively the readLine() and readAll() convenience methods can also be invoked. The SerialPort class also inherits the getChar(), putChar(), and ungetChar() methods from the QIODevice class. Those methods work on single bytes. The bytesWritten() signal is emitted when data has been written to the serial port. Note that, Qt does not limit the write buffer size, which can be monitored by listening to this signal.

The readyRead() signal is emitted every time a new chunk of data has arrived. The bytesAvailable() method then returns the number of bytes that are available for reading. Typically, the readyRead() signal would be connected to a slot and all data available could be read in there.

If not all the data is read at once, the remaining data will still be available later. Any new incoming data will be appended to the SerialPort's internal read buffer. In order to limit the size of the read buffer, call setReadBufferSize().

The status of the control lines is determined with the dtr(), rts(), and lines() methods. To change the control line status, use the setDtr(), and setRts() methods.

To close the serial port, call the close() method. After all the pending data has been written to the serial port, the SerialPort class actually closes the descriptor.

SerialPort 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:

See the following example:

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

    forever {
        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.

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.

See the examples/terminal and examples/blockingterminal examples for an overview of both approaches.

The use of blocking functions is discouraged together with signals. One of the two possibilities should be used.

The SerialPort class can 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 SerialPortInfo.

Member Type Documentation

enum SerialPort::DataBits

This enum describes the number of data bits used.

ConstantValueDescription
SerialPort::Data55Five bits.
SerialPort::Data66Six bits.
SerialPort::Data77Seven bits
SerialPort::Data88Eight bits.
SerialPort::UnknownDataBits-1Unknown number of bits.

See also setDataBits() and dataBits().

enum SerialPort::DataErrorPolicy

This enum describes the policies for the received symbols while parity errors were detected.

ConstantValueDescription
SerialPort::SkipPolicy0Skips the bad character.
SerialPort::PassZeroPolicy1Replaces bad character to zero.
SerialPort::IgnorePolicy2Ignores the error for a bad character.
SerialPort::StopReceivingPolicy3Stops data reception on error.
SerialPort::UnknownPolicy-1Unknown policy.

See also setDataErrorPolicy() and dataErrorPolicy().

enum SerialPort::Direction
flags SerialPort::Directions

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 in case some operating systems (i.e. POSIX-like).

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

The Directions type is a typedef for QFlags<Direction>. It stores an OR combination of Direction values.

enum SerialPort::FlowControl

This enum describes the flow control used.

ConstantValueDescription
SerialPort::NoFlowControl0No flow control.
SerialPort::HardwareControl1Hardware flow control (RTS/CTS).
SerialPort::SoftwareControl2Software flow control (XON/XOFF).
SerialPort::UnknownFlowControl-1Unknown flow control.

See also setFlowControl() and flowControl().

enum SerialPort::Line
flags SerialPort::Lines

This enum describes the possible RS-232 pinout signals.

ConstantValueDescription
SerialPort::Le?DSR (data set ready/line enable).
SerialPort::Dtr?DTR (data terminal ready).
SerialPort::Rts?RTS (request to send).
SerialPort::St?Secondary TXD (transmit).
SerialPort::Sr?Secondary RXD (receive).
SerialPort::Cts?CTS (clear to send).
SerialPort::Dcd?DCD (data carrier detect).
SerialPort::Ri?RNG (ring).
SerialPort::Dsr?DSR (data set ready).

The Lines type is a typedef for QFlags<Line>. It stores an OR combination of Line values.

See also lines(), setDtr(), setRts(), dtr(), and rts().

enum SerialPort::Parity

This enum describes the parity scheme used.

\ValueNoParity No parity.

ConstantValueDescription
SerialPort::EvenParity2Even parity.
SerialPort::OddParity3Odd parity.
SerialPort::SpaceParity4Space parity.
SerialPort::MarkParity5Mark parity.
SerialPort::UnknownParity-1Unknown parity.

See also setParity() and parity().

enum SerialPort::PortError

This enum describes the errors that may be returned by the error() method.

ConstantValueDescription
SerialPort::NoError0No error occurred.
SerialPort::NoSuchDeviceError1An error occurred while attempting to open an non-existing device.
SerialPort::PermissionDeniedError2An error occurred while attempting to open an already opened device by another process or a user not having enough permission and credentials to open.
SerialPort::DeviceAlreadyOpenedError3An error occurred while attempting to open an already opened device in this object.
SerialPort::DeviceIsNotOpenedError4An error occurred while attempting to control a device still closed.
SerialPort::ParityError5Parity error detected by the hardware while reading data.
SerialPort::FramingError6Framing error detected by the hardware while reading data.
SerialPort::BreakConditionError7Break condition detected by the hardware on the input line.
SerialPort::IoError8An I/O error occurred while reading or writing the data.
SerialPort::UnsupportedPortOperationError9The requested device operation is not supported or prohibited by the running operating system.
SerialPort::UnknownPortError10An unidentified error occurred.

See also error() and clearError().

enum SerialPort::Rate

This enum describes the baud rate which the communication device operates with. Note: only the most common standard rates are listed in this enum.

ConstantValueDescription
SerialPort::Rate120012001200 baud.
SerialPort::Rate240024002400 baud.
SerialPort::Rate480048004800 baud.
SerialPort::Rate960096009600 baud.
SerialPort::Rate192001920019200 baud.
SerialPort::Rate384003840038400 baud.
SerialPort::Rate576005760057600 baud.
SerialPort::Rate115200115200115200 baud.
SerialPort::UnknownRate-1Unknown baud.

See also setRate() and rate().

enum SerialPort::StopBits

This enum describes the number of stop bits used.

ConstantValueDescription
SerialPort::OneStop11 stop bit.
SerialPort::OneAndHalfStop31.5 stop bits.
SerialPort::TwoStop22 stop bits.
SerialPort::UnknownStopBits-1Unknown number of stop bit.

See also setStopBits() and stopBits().

Property Documentation

dataBits : DataBits

This property holds the data bits in a frame.

If the setting is successful, returns true; otherwise returns false and sets an error code which can be obtained by calling the error() method.

Access functions:

DataBits dataBits () const
bool setDataBits ( DataBits dataBits )

Notifier signal:

void dataBitsChanged ( DataBits dataBits )

dataErrorPolicy : DataErrorPolicy

This property holds the error policy how the process receives the character in case of parity error detection.

If the setting is successful, returns true; otherwise returns false. The default policy set is IgnorePolicy.

Access functions:

DataErrorPolicy dataErrorPolicy () const
bool setDataErrorPolicy ( DataErrorPolicy policy = IgnorePolicy )

Notifier signal:

void dataErrorPolicyChanged ( DataErrorPolicy policy )

dtr : bool

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

If the setting is successful, returns true; otherwise returns false. If the flag is true then the DTR signal is set to high; otherwise low.

Access functions:

bool dtr () const
bool setDtr ( bool set )

Notifier signal:

void dtrChanged ( bool set )

See also lines().

error : PortError

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

Access functions:

PortError error () const
void clearError ()

Notifier signal:

void errorChanged ( PortError error )

flowControl : FlowControl

This property holds the desired flow control mode.

If the setting is successful, returns true; otherwise returns false and sets an error code which can be obtained by calling the error() method.

Access functions:

FlowControl flowControl () const
bool setFlowControl ( FlowControl flow )

Notifier signal:

void flowControlChanged ( FlowControl flow )

parity : Parity

This property holds the parity checking mode.

If the setting is successful, returns true; otherwise returns false and sets an error code which can be obtained by calling the error() method.

Access functions:

Parity parity () const
bool setParity ( Parity parity )

Notifier signal:

void parityChanged ( Parity parity )

rate : qint32

This property holds the data rate for the desired direction.

If the setting is successful, returns true; otherwise returns false and sets an error code which can be obtained by calling error(). To set the baud rate, use the enumeration SerialPort::Rate or any positive qint32 value.

Warning: Only the AllDirections flag is support for setting this property on Windows, Windows CE, and Symbian.

Warning: Returns equal rate in any direction on Windows, Windows CE, and Symbian.

Access functions:

qint32 rate ( Directions dir = AllDirections ) const
bool setRate ( qint32 rate, Directions dir = AllDirections )

Notifier signal:

void rateChanged ( qint32 rate, Directions dir )

restoreSettingsOnClose : bool

This property holds the flag which allows to restore the previous settings while closing the serial port.

If this flag is true, the settings will be restored; otherwise not. The default state of the SerialPort class is configured to restore the settings.

Access functions:

bool restoreSettingsOnClose () const
void setRestoreSettingsOnClose ( bool restore )

Notifier signal:

void restoreSettingsOnCloseChanged ( bool restore )

See also restoreSettingsOnClose().

rts : bool

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

If the setting is successful, returns true; otherwise returns false. If the flag is true then the RTS signal is set to high; otherwise low.

Access functions:

bool rts () const
bool setRts ( bool set )

Notifier signal:

void rtsChanged ( bool set )

See also lines().

stopBits : StopBits

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

If the setting is successful, returns true; otherwise returns false and sets an error code which can be obtained by calling the error() method.

Access functions:

StopBits stopBits () const
bool setStopBits ( StopBits stopBits )

Notifier signal:

void stopBitsChanged ( StopBits stopBits )

Member Function Documentation

SerialPort::SerialPort ( QObject * parent = 0 )

Constructs a new serial port object with the given parent.

SerialPort::SerialPort ( const QString & name, QObject * parent = 0 )

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.

SerialPort::SerialPort ( const SerialPortInfo & info, QObject * parent = 0 )

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

SerialPort::~SerialPort () [virtual]

Closes the serial port, if neccessary, and then destroys object.

bool SerialPort::atEnd () const [virtual]

Reimplemented from QIODevice::atEnd().

Returns true if no more data is currently available for reading; otherwise returns false.

This function is most commonly used when reading data from the serial port in a loop. For example:

    // This slot is connected to SerialPort::readyRead()
    void SerialPortClass::readyReadSlot()
    {
        while (!port.atEnd()) {
            QByteArray data = port.read(100);
            ....
        }
    }

See also bytesAvailable() and readyRead().

qint64 SerialPort::bytesAvailable () const [virtual]

Reimplemented from QIODevice::bytesAvailable().

Returns the number of incoming bytes that are waiting to be read.

See also bytesToWrite() and read().

qint64 SerialPort::bytesToWrite () const [virtual]

Reimplemented from QIODevice::bytesToWrite().

Returns the number of bytes that are waiting to be written. The bytes are written when control goes back to the event loop or when flush() is called.

See also bytesAvailable() and flush().

bool SerialPort::canReadLine () const [virtual]

Reimplemented from QIODevice::canReadLine().

Returns true if a line of data can be read from the serial port; otherwise returns false.

See also readLine().

bool SerialPort::clear ( Directions dir = AllDirections )

Discards all characters from the output or input buffer, depending on a given direction dir. Including clear an internal class buffers and the UART (driver) buffers. Also terminate pending read or write operations. If successful, returns true; otherwise returns false.

bool SerialPort::clearBreak ( bool clear = true ) [slot]

Controls the signal break, depending on the flag clear. If successful, returns true; otherwise returns false.

If clear is false then enables the break transmission; otherwise disables.

See also setBreak() and sendBreak().

void SerialPort::close () [virtual]

Reimplemented from QIODevice::close().

Calls SerialPort::flush() and closes the serial port. Errors from flush are ignored.

See also QIODevice::close().

void SerialPort::dataBitsChanged ( DataBits dataBits ) [signal]

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 SerialPort::dataBits.

void SerialPort::dataErrorPolicyChanged ( DataErrorPolicy policy ) [signal]

void SerialPort::dtrChanged ( bool set ) [signal]

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 SerialPort::dtr.

void SerialPort::errorChanged ( PortError error ) [signal]

This signal is emitted after the error has been changed. The new erroris passed as error.

See also SerialPort::error.

void SerialPort::flowControlChanged ( FlowControl flow ) [signal]

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

See also SerialPort::flowControl.

bool SerialPort::flush ()

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 SerialPort class will start sending data automatically once control is returned to the event loop. In the absence of an event loop, call waitForBytesWritten() instead.

See also write() and waitForBytesWritten().

bool SerialPort::isSequential () const [virtual]

Reimplemented from QIODevice::isSequential().

Always returns true. The serial port is a sequential device.

Lines SerialPort::lines () const

Returns the bitmap states of the line signals. 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 SerialPort::Lines.

See also dtr(), rts(), setDtr(), and setRts().

bool SerialPort::open ( OpenMode mode ) [virtual]

Opens the serial port using OpenMode mode, and then returns true if successful; otherwise returns false with and sets an error code which can be obtained by calling the error() method.

Warning: The mode has to be QIODevice::ReadOnly, QIODevice::WriteOnly, or QIODevice::ReadWrite. This may also have additional flags, such as QIODevice::Unbuffered. Other modes are unsupported.

See also QIODevice::OpenMode and setPort().

void SerialPort::parityChanged ( Parity parity ) [signal]

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

See also SerialPort::parity.

QString SerialPort::portName () const

Returns the name set by setPort() or to the SerialPort constructors. This name is short, i.e. it extract and convert out from the internal variable system location of the device. Conversion algorithm is platform specific:

PlatformBrief Description
WindowsRemoves the prefix "\\.\" from the system location and returns the remainder of the string.
Windows CERemoves the postfix ":" from the system location and returns the remainder of the string.
SymbianReturns the system location as it is, as it is equivalent to the port name.
GNU/LinuxRemoves the prefix "/dev/" from the system location and returns the remainder of the string.
Mac OSXRemoves the prefix "/dev/cu." and "/dev/tty." from the system location and returns the remainder of the string.
Other *nixThe same as for GNU/Linux.

See also setPort() and SerialPortInfo::portName().

void SerialPort::rateChanged ( qint32 rate, Directions dir ) [signal]

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

See also SerialPort::rate.

qint64 SerialPort::readBufferSize () const

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.

See also setReadBufferSize() and read().

qint64 SerialPort::readData ( char * data, qint64 maxSize ) [virtual protected]

Reimplemented from QIODevice::readData().

qint64 SerialPort::readLineData ( char * data, qint64 maxSize ) [virtual protected]

Reimplemented from QIODevice::readLineData().

void SerialPort::restoreSettingsOnCloseChanged ( bool restore ) [signal]

This signal is emitted after the flag which allows to restore the previous settings while closing the serial port has been changed. The new flag which allows to restore the previous settings while closing the serial port is passed as \restore.

See also SerialPort::restoreSettingsOnClose.

void SerialPort::rtsChanged ( bool set ) [signal]

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 SerialPort::rts.

bool SerialPort::sendBreak ( int duration = 0 ) [slot]

Sends a continuous stream of zero bits during a specified period of time duration in msec if the terminal is using asynchronous serial data. If successful, returns true; otherwise returns false.

If the duration is zero then zero bits are transmitted by at least 0.25 seconds, but no more than 0.5 seconds.

If the duration is non zero then zero bits are transmitted within a certain period of time depending on the implementation.

See also setBreak() and clearBreak().

bool SerialPort::setBreak ( bool set = true ) [slot]

Controls the signal break, depending on the flag set. If successful, returns true; otherwise returns false.

If set is true then enables the break transmission; otherwise disables.

See also clearBreak() and sendBreak().

void SerialPort::setPort ( const QString & name )

Sets the name of the port. The name may be in any format; either short, or also as system location (with all the prefixes and postfixed). As a result, this name will be automatically written and converted into an internal variable as system location.

See also portName() and SerialPortInfo.

void SerialPort::setPort ( const SerialPortInfo & info )

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

See also portName() and SerialPortInfo.

void SerialPort::setReadBufferSize ( qint64 size )

Sets the size of SerialPort's internal read buffer to be size bytes.

If the buffer size is limited to a certain size, SerialPort will not buffer more than this size of data. Exceptionally, 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 causes that the application runs out of memory.

See also readBufferSize() and read().

void SerialPort::stopBitsChanged ( StopBits stopBits ) [signal]

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 SerialPort::stopBits.

bool SerialPort::waitForBytesWritten ( int msecs ) [virtual]

Reimplemented from QIODevice::waitForBytesWritten().

bool SerialPort::waitForReadyRead ( int msecs ) [virtual]

Reimplemented from QIODevice::waitForReadyRead().

This function blocks until new data is available for reading and the readyRead() signal has been emitted. The function will timeout after msecs milliseconds.

The function returns true if the readyRead() signal is emitted and there is new data available for reading; otherwise it returns false (if an error occurred or the operation timed out).

See also waitForBytesWritten().

qint64 SerialPort::writeData ( const char * data, qint64 maxSize ) [virtual protected]

Reimplemented from QIODevice::writeData().