QSerialPort

13 篇文章 0 订阅

Contents
Public Types
Properties
Public Functions
Reimplemented Public Functions
Signals
Reimplemented Protected Functions
Detailed Description
QSerialPort Class
Provides functions to access serial ports. More…

Header:

include

qmake:
QT += serialport
Since:
Qt 5.1
Inherits:
QIODevice

List of all members, including inherited members
Obsolete members
Note: All functions in this class are reentrant.
Public Types

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

Properties

baudRate : qint32
breakEnabled : bool
dataBits : DataBits
dataTerminalReady : bool
error : SerialPortError
flowControl : FlowControl
parity : Parity
requestToSend : bool
stopBits : StopBits

1 property inherited from QObject
Public Functions

QSerialPort(QObject *parent = Q_NULLPTR)

QSerialPort(const QString &name, QObject *parent = Q_NULLPTR)

QSerialPort(const QSerialPortInfo &serialPortInfo, QObject *parent = Q_NULLPTR)
virtual
~QSerialPort()
qint32
baudRate(Directions directions = AllDirections) const
bool
clear(Directions directions = AllDirections)
void
clearError()
DataBits
dataBits() const
SerialPortError
error() const
FlowControl
flowControl() const
bool
flush()
Handle
handle() const
bool
isBreakEnabled() const
bool
isDataTerminalReady()
bool
isRequestToSend()
Parity
parity() const
PinoutSignals
pinoutSignals()
QString
portName() const
qint64
readBufferSize() const
(deprecated) bool
sendBreak(int duration = 0)
bool
setBaudRate(qint32 baudRate, Directions directions = AllDirections)
bool
setBreakEnabled(bool set = true)
bool
setDataBits(DataBits dataBits)
bool
setDataTerminalReady(bool set)
bool
setFlowControl(FlowControl flowControl)
bool
setParity(Parity parity)
void
setPort(const QSerialPortInfo &serialPortInfo)
void
setPortName(const QString &name)
void
setReadBufferSize(qint64 size)
bool
setRequestToSend(bool set)
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
open(OpenMode mode)
virtual bool
waitForBytesWritten(int msecs)
virtual bool
waitForReadyRead(int msecs)

43 public functions inherited from QIODevice
31 public functions inherited from QObject
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 error)
void
flowControlChanged(QSerialPort::FlowControl flow)
void
parityChanged(QSerialPort::Parity parity)
void
requestToSendChanged(bool set)
void
stopBitsChanged(QSerialPort::StopBits stopBits)

6 signals inherited from QIODevice
2 signals inherited from QObject
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)

5 protected functions inherited from QIODevice
9 protected functions inherited from QObject
Additional Inherited Members
1 public slot inherited from QObject
1 public variable inherited from QObject
10 static public members inherited from QObject
5 protected functions inherited from QIODevice
9 protected functions inherited from QObject
2 protected variables inherited from QObject
Detailed Description
Provides functions to access serial ports.
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).
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().
Use the close() method to close the port and cancel the I/O operations.
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.
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.

Constant
Value
Description
QSerialPort::Baud1200
1200
1200 baud.
QSerialPort::Baud2400
2400
2400 baud.
QSerialPort::Baud4800
4800
4800 baud.
QSerialPort::Baud9600
9600
9600 baud.
QSerialPort::Baud19200
19200
19200 baud.
QSerialPort::Baud38400
38400
38400 baud.
QSerialPort::Baud57600
57600
57600 baud.
QSerialPort::Baud115200
115200
115200 baud.
QSerialPort::UnknownBaud
-1
Unknown 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.

Constant
Value
Description
QSerialPort::Data5
5
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
6
The number of data bits in each character is 6. It is rarely used.
QSerialPort::Data7
7
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
8
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.
QSerialPort::UnknownDataBits
-1
Unknown 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
flags QSerialPort::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 on some operating systems (for example, POSIX-like).

Constant
Value
Description
QSerialPort::Input
1
Input direction.
QSerialPort::Output
2
Output direction.
QSerialPort::AllDirections
Input | Output
Simultaneously in two directions.

The Directions type is a typedef for QFlags. It stores an OR combination of Direction values.
enum QSerialPort::FlowControl
This enum describes the flow control used.

Constant
Value
Description
QSerialPort::NoFlowControl
0
No flow control.
QSerialPort::HardwareControl
1
Hardware flow control (RTS/CTS).
QSerialPort::SoftwareControl
2
Software flow control (XON/XOFF).
QSerialPort::UnknownFlowControl
-1
Unknown 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.

Constant
Value
Description
QSerialPort::NoParity
0
No parity bit it sent. This is the most common parity setting. Error detection is handled by the communication protocol.
QSerialPort::EvenParity
2
The number of 1 bits in each character, including the parity bit, is always even.
QSerialPort::OddParity
3
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
4
Space parity. The parity bit is sent in the space signal condition. It does not provide error detection information.
QSerialPort::MarkParity
5
Mark parity. The parity bit is always set to the mark signal condition (logical 1). It does not provide error detection information.
QSerialPort::UnknownParity
-1
Unknown 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
flags QSerialPort::PinoutSignals
This enum describes the possible RS-232 pinout signals.

Constant
Value
Description
QSerialPort::NoSignal
0x00
No line active
QSerialPort::TransmittedDataSignal
0x01
TxD (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::ReceivedDataSignal
0x02
RxD (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::DataTerminalReadySignal
0x04
DTR (Data Terminal Ready).
QSerialPort::DataCarrierDetectSignal
0x08
DCD (Data Carrier Detect).
QSerialPort::DataSetReadySignal
0x10
DSR (Data Set Ready).
QSerialPort::RingIndicatorSignal
0x20
RNG (Ring Indicator).
QSerialPort::RequestToSendSignal
0x40
RTS (Request To Send).
QSerialPort::ClearToSendSignal
0x80
CTS (Clear To Send).
QSerialPort::SecondaryTransmittedDataSignal
0x100
STD (Secondary Transmitted Data).
QSerialPort::SecondaryReceivedDataSignal
0x200
SRD (Secondary Received Data).

The PinoutSignals type is a typedef for QFlags. It stores an OR combination of PinoutSignal values.
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.

Constant
Value
Description
QSerialPort::NoError
0
No error occurred.
QSerialPort::DeviceNotFoundError
1
An error occurred while attempting to open an non-existing device.
QSerialPort::PermissionError
2
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
3
An error occurred while attempting to open an already opened device in this object.
QSerialPort::NotOpenError
13
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::ParityError
4
Parity error detected by the hardware while reading data. This value is obsolete. We strongly advise against using it in new code.
QSerialPort::FramingError
5
Framing error detected by the hardware while reading data. This value is obsolete. We strongly advise against using it in new code.
QSerialPort::BreakConditionError
6
Break condition detected by the hardware on the input line. This value is obsolete. We strongly advise against using it in new code.
QSerialPort::WriteError
7
An I/O error occurred while writing the data.
QSerialPort::ReadError
8
An I/O error occurred while reading the data.
QSerialPort::ResourceError
9
An I/O error occurred when a resource becomes unavailable, e.g. when the device is unexpectedly removed from the system.
QSerialPort::UnsupportedOperationError
10
The requested device operation is not supported or prohibited by the running operating system.
QSerialPort::TimeoutError
12
A timeout error occurred. This value was introduced in QtSerialPort 5.2.
QSerialPort::UnknownError
11
An unidentified error occurred.

See also QSerialPort::error.
enum QSerialPort::StopBits
This enum describes the number of stop bits used.

Constant
Value
Description
QSerialPort::OneStop
1
1 stop bit.
QSerialPort::OneAndHalfStop
3
1.5 stop bits. This is only for the Windows platform.
QSerialPort::TwoStop
2
2 stop bits.
QSerialPort::UnknownStopBits
-1
Unknown 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 and Windows CE support only this mode.
Warning: Returns equal baud rate in any direction on Windows, Windows CE.
The default value is Baud9600, i.e. 9600 bits per second.
Access functions:

qint32
baudRate(Directions directions = AllDirections) const
bool
setBaudRate(qint32 baudRate, 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:

DataBits
dataBits() const
bool
setDataBits(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:

SerialPortError
error() const
void
error(QSerialPort::SerialPortError error)
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:

FlowControl
flowControl() const
bool
setFlowControl(FlowControl flowControl)

Notifier signal:

void
flowControlChanged(QSerialPort::FlowControl flow)

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:

Parity
parity() const
bool
setParity(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.
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:

StopBits
stopBits() const
bool
setStopBits(StopBits stopBits)

Notifier signal:

void
stopBitsChanged(QSerialPort::StopBits stopBits)

Member Function Documentation
QSerialPort::QSerialPort(QObject *parent = Q_NULLPTR)
Constructs a new serial port object with the given parent.
QSerialPort::QSerialPort(const QString &name, QObject *parent = Q_NULLPTR)
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.
QSerialPort::QSerialPort(const QSerialPortInfo &serialPortInfo, QObject *parent = Q_NULLPTR)
Constructs a new serial port object with the given parent to represent the serial port with the specified helper class serialPortInfo.
[virtual] QSerialPort::~QSerialPort()
Closes the serial port, if necessary, and then destroys object.
[virtual] bool QSerialPort::atEnd() const
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 QSerialPort::readyRead()
void QSerialPortClass::readyReadSlot()
{
while (!port.atEnd()) {
QByteArray data = port.read(100);
….
}
}

See also bytesAvailable() and readyRead().
[signal] void QSerialPort::baudRateChanged(qint32 baudRate, QSerialPort::Directions directions)
This signal is emitted after the baud rate has been changed. The new baud rate is passed as baudRate and directions as directions.
Note: Notifier signal for property baudRate.
See also QSerialPort::baudRate.
[virtual] qint64 QSerialPort::bytesAvailable() const
Reimplemented from QIODevice::bytesAvailable().
Returns the number of incoming bytes that are waiting to be read.
See also bytesToWrite() and read().
[virtual] qint64 QSerialPort::bytesToWrite() const
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().
[virtual] bool QSerialPort::canReadLine() const
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 QSerialPort::clear(Directions directions = AllDirections)
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.
[virtual] void QSerialPort::close()
Reimplemented from QIODevice::close().
Note: The serial port has to be open before trying to close it; otherwise sets the NotOpenError error code.
See also QIODevice::close().
[signal] void QSerialPort::dataBitsChanged(QSerialPort::DataBits dataBits)
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.
Note: Notifier signal for property dataBits.
See also QSerialPort::dataBits.
[signal] void QSerialPort::dataTerminalReadyChanged(bool set)
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.
Note: Notifier signal for property dataTerminalReady.
See also QSerialPort::dataTerminalReady.
[signal] void QSerialPort::error(QSerialPort::SerialPortError error)
This signal is emitted after the error has been changed. The new error is passed as error.
Note: Signal error is overloaded in this class. To connect to this one using the function pointer syntax, you must specify the signal type in a static cast, as shown in this example:

connect(serialPort, static_cast

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值