QT串口编程的相关类2(QSerialPort)

QT Serial Port相关的类只有两个QSerialPortInfo(#include) 和QserialPort(#include)

在http://blog.csdn.net/mcu_tian/article/details/43527385介绍过QSerialPortInfo串口辅助类

下面介绍QSerialPort类

QserialPort

该类的主要功能是提供接口访问串口,对串口进行配置(如波特率,校验位,停止位等),读写功能。

我们可以调用QSerialPortInfo辅助类获取可用串口的信息的参数,再通过QT Serial Port类的setPort()等成员函数分配串口设备。

在给串口分配过过串口设备之后(也就是给QSerialPort的对象分配过特定端口口之后),我们得先调用open打开该串口,在open成功返回之后,再进行该串口的波特率,停止位,校验位等的配置。当调用成员函数waitForReadyRead()看是否已经准备好读写之后,再调用该类的write和read等成员函数进行读写。

ps:Qserialport只支持端口的互斥操作(同步操作),只有该进程可以对某个对打开的端口进行操作,不能操作其他进程已经打开正在占用的端口了。


跨平台是QT的优势,QserialPort支持的平台QT WIKI截图如下:

QT串口编程的相关类2(QSerialPort)_第1张图片

下面来详细介绍QSerialPort的成员以及功能

其public成员函数分为几类

1:构造函数

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

以上三个构造函数是在接受不同的参数创建对象。

2:析构函数

virtual~QSerialPort()

3:端口功能函数

该类函数主要是是对端口的配置,操作,读写,以及当前状态的读取等

voidsetPortName(const QString & name)
设置QSerialPort对象的端口名,将该对象与端口所对应的端口绑定
void ​setPort(const QSerialPortInfo & serialPortInfo)
绑定对象与特定可用的端口,该端口的信息通过QSerialPortInfo对象传递
QString portName() const
取得该对象所对应的端口名

boolsetBaudRate(qint32 baudRate, Directions directions = AllDirections)

该函数的功能是设置该波特率,形参qint32 baundRate 要设置的波特的值,对象的默认的值为9600。

对应于波特率所对应于枚举常量如下

ConstantValueDescription
QSerialPort::Baud1200 12001200 baud.
QSerialPort::Baud2400 24002400 baud.
QSerialPort::Baud4800 48004800 baud.
QSerialPort::Baud9600 96009600 baud.
QSerialPort::Baud19200 1920019200 baud.
QSerialPort::Baud38400 3840038400 baud.
QSerialPort::Baud57600 5760057600 baud.
QSerialPort::Baud115200 115200115200 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.


Directions directions 是指定设置是输入还是输出的的波特率。该参数有类提供的枚举,一共有三种选择如下。

ConstantValueDescription
QSerialPort::Input 1Input direction.
QSerialPort::Output 2Output direction.
QSerialPort::AllDirections Input | OutputSimultaneously in two directions.

默认的形参是ALLDirection,但是需要注意的是,支持该参数的只有windows、wince、以及塞班平台

qint32baudRate(Directions directions = AllDirections) const

该函数主要功能返回该端口的波特率的值,其形参选择如上。

boolclear(Directions directions = AllDirections)

该函数的功能是根据传入的参数清空缓冲区

boolsetStopBits(StopBits stopBits)
设置端口的停止位
StopBits stopBits() const
取得该对象所对应的端口位的停止位配置信息
stopbits有对应于对应于的枚举常量如下,分别对应于1、1.5、2个停止位
QSerialPort::OneStop 11 stop bit.
QSerialPort::OneAndHalfStop 31.5 stop bits. This is only for the Windows platform.
QSerialPort::TwoStop 22 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.

SerialPortErrorerror() const
当操作端口发生错误的时候(例如open该端口失败时),调用SerialPortErrorerror() const,返回SerialPortError型数据,指明是哪里出错了。返回的错误值对应于error的枚举常量如下:

QSerialPort::NoError0No 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.
QSerialPort::FramingError 5Framing error detected by the hardware while reading data.
QSerialPort::BreakConditionError 6 Break condition detected by the hardware on the input line.
QSerialPort::WriteError 7 An I/O error occurred while writing the data.
QSerialPort::ReadError 8An 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  10The requested device operation is not supported or prohibited by the running operating system.
QSerialPort::TimeoutError  12Atimeout error occurred. This value was introduced in QtSerialPort 5.2.
QSerialPort::UnknownError 11 An unidentified error occurred.

voidclearError() 在产生错误之后,调用该clearError()函数之后,清除之前的报错出错信息。

DataBitsdataBits() const  该函数主要功能是返回当前状态数据帧的数据位位数。
bool setDataBits(DataBits dataBits)   设置在发送数据时,数据的数据位数,在默认的情况下,有效数据位数为8位

对应于数据位的枚举常量如下,有5到8位数据位
QSerialPort::Data5 5The 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 6The number of data bits in each character is 6. It is rarely used.
QSerialPort::Data7 7The 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 8The 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.

FlowControlflowControl() const   该函数主要功能是返回当前的进程对数据流量的控制状态
bool setFlowControl(FlowControl flowControl)    该函数主要是设置对数据流量的控制。

对于数据流量的控制主要有以下几种情况:不控制,硬件控制,软件控制,以及未知流量控制。其对应的枚举常量如下

ConstantValueDescription
QSerialPort::NoFlowControl    0No flow control.
QSerialPort::HardwareControl    1Hardware flow control (RTS/CTS).
QSerialPort::SoftwareControl     2Software 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.

boolflush()    该函数的主要功能是刷新该写缓冲区,使数据尽快的写入到端口中。不过在一般情况下不会用到该函数,数据写入到端口系统会自动去控制。

Handle handle() const   该函数测试平台是否支持以及是否有串口打开,若是没有返回-1

bool    isDataTerminalReady()    串口终端设备是否有准备,若是准备好了返回true 否则返回false


Parity parity() const  该函数的主要功能是返回端口的奇偶检验位的配置信息
bool setParity(Parity parity)   该函数的主要功能是设置奇偶校验位

奇偶校验位的对应的枚举常量如下:

Constant ValueDescription
QSerialPort::NoParity        0No parity bit it sent. This is the most common parity setting. Error detection is handled by the communication protocol.
QSerialPort::EvenParity    2The number of 1 bits in each character, including the parity bit, is always even.
QSerialPort::OddParity    3The 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    4Space parity. The parity bit is sent in the space signal condition. It does not provide error detection information.
QSerialPort::MarkParity     5Mark 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.

qint64readBufferSize() const
返回端口的读缓冲区的大小,该缓冲区用qint64数据类型表示
void QSerialPort::​setReadBufferSize(qint64 size)
设置端口读写缓冲区的大小。
bool sendBreak(int duration = 0)
在端口设备终端使用异步串口模式的时候,在毫秒量级的时间内连续发送一串连续的值为0的bit流
发送成功则为返回true否则返回false
bool ​setBreakEnabled(bool set = true)
使能break信号
bool setDataTerminalReady(bool set)
设置端口终端准备准备信号状态

4,重载继承函数
下面几个函数继承于QIODevice,并进行了重载
virtual bool atEnd() const
主要功能是判断是否有还有可读数据,若是没有,则返回true,否则返回false
例如
while (!port.atEnd()) {
        QByteArray data = port.read(100);
        }
ps:是否有数据可读,若是有数据可读(false),则读入数据,知道数据读完位置。
virtual qint64 bytesAvailable() const
主要功能是返回有多少字节可读数据
virtual qint64 bytesToWrite() const
主要功能是查询有多少字节待写入端口的数据。
virtual bool canReadLine() const
判断在端口是否有一行的数据可以读,若是有的话返回true,否则返回false
virtual void close()
关闭该端口,释放对象所对应端口。ps:必须是open成功之后,才能使用此函数,否则会报错
virtual bool open(OpenMode mode)
打开对象所对应的串口设备,其打开后的操作模式跟传入形参OpenMode mode有关
操作模式有 只读、只写、读写、后面添加等
其模式对应于的类的枚举常量如下
Constant ValueDescription
QIODevice::NotOpen 0x0000The device is not open.
QIODevice::ReadOnly 0x0001The device is open for reading.
QIODevice::WriteOnly 0x0002The device is open for writing. Note that this mode implies Truncate.
QIODevice::ReadWrite  ReadOnly | WriteOnly The device is open for reading and writing.
QIODevice::Append 0x0004The device is opened in append mode so that all data is written to the end of the file.
QIODevice::Truncate 0x0008If possible, the device is truncated before it is opened. All earlier contents of the device are lost.
QIODevice::Text 0x0010When reading, the end-of-line terminators are translated to '\n'. When writing, the end-of-line terminators are translated to the local encoding, for example '\r\n' for Win32.
QIODevice::Unbuffered 0x0020Any buffer in the device is bypassed.
virtual bool waitForReadyRead(int msecs)
这个函数将会阻塞进程,一直到有新的可读数据来了 readyRead() 发射信号为止。
或者在阻塞超过msecs后,无新的可读数据,函数超时,将会返回false
5,signal函数
以下几个是Qserialport类的signal函数,在调用该类函数的时候,会产生一个signal
若是有绑定对应的slot函数,slot函数将会响应该signal
void baudRateChanged(qint32 baudRate, QSerialPort::Directions directions)
改变对象对应端口的波特率
参数跟bool  setBaudRate()完全一样,参照前面该函数
void dataBitsChanged(QSerialPort::DataBits dataBits)
改变对象对应端口的数据的数据位数
参数跟bool  setDataBits(DataBits dataBits)完全一样,参照前面该函数
void dataTerminalReadyChanged(bool set)
设置新的data ready 信号
参数与bool  setDataTerminalReady(bool set) 一样,参照前面该函数
void error(QSerialPort::SerialPortError error)
有错误产生,并将错误的类型error传给该函数,将会产生一个signal信号
void flowControlChanged(QSerialPort::FlowControl flow)
改变对象对应端口的流量控制情况
参数跟bool  setFlowControl(FlowControl flowControl)完全一样,参照前面该函数
void parityChanged(QSerialPort::Parity parity)
改变对象对应端口的奇偶校验位
参数跟bool  setParity(Parity parity)完全一样,参照前面该函数
void stopBitsChanged(QSerialPort::StopBits stopBits)
改变对象对应端口的停止位
参数跟bool  setStopBits(StopBits stopBits)完全一样,参照前面该函数


6,重载继承protected函数
下面几个函数继承于QIODevice,并进行了重载
virtual qint64 readData(char * data, qint64 maxSize)
该函数的主要功能是读取数据,数据的存放缓冲区在char * data所指向的指针,
读取的最大字节数目为maxSize,返回实际读取到的字节数目
virtual qint64 readLineData(char * data, qint64 maxSize)
用法和readData几乎一样,但是会在读取的数据是行,不是字节流。所返回的也是读取的数据的数目。
virtual qint64 writeData(const char * data, qint64 maxSize)
该函数的主要功能是写入数据,数据的存放缓冲区在char * data所指向的指针,
写入的最大字节数目为maxSize,返回实际读取到的字节数目

关于实例将在后面的博文中再说,若是有什么错误的地方,欢迎指正,感激不尽!







你可能感兴趣的:(QT)