Qt串口QSerialPort

什么是串口

  1. 串口是一种物理端口,类似于HDMI口,DP口,USB口,Lighting,Type-C等。串口又名串行端口、COM口。
  2. 串口的数据和控制信息是一位接一位地传输出去的。速度较慢,但是传输距离较远。

Qt模块支持

# pro文件
QT += serialport

# 头文件
#include <QSerialPort>

串口参数

  1. 波特率
    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.

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)
  1. 数据位
    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.

Access functions:

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

Notifier signal:

void dataBitsChanged(QSerialPort::DataBits dataBits)
  1. 停止位
    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.

Access functions:

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

Notifier signal:

void stopBitsChanged(QSerialPort::StopBits stopBits)
  1. 奇偶校验位
    一种检错方式,有四种:奇校验,偶校验,高校验,低校验,当然也可以不校验
    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.

Access functions:

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

Notifier signal:

void parityChanged(QSerialPort::Parity parity)

打开串口

  1. QSerialPortInfo
    为存在的串口提供参数信息

[static] QList QSerialPortInfo::availablePorts()
Returns a list of available serial ports on the system.

// 获取可用串口
QSerialPortInfo::availablePorts();
  1. 打开串口
    a. open

[virtual] bool QIODevice::open(QIODevice::OpenMode mode)
Opens the device and sets its OpenMode to mode. Returns true if successful; otherwise returns false. This function should be called from any reimplementations of open() or other functions that open the device.

b. OpenMode

enum QIODevice::OpenModeFlag
flags QIODevice::OpenModeThis enum is used with open() to describe the mode in which a device is opened. It is also returned by openMode().

Constant Value Description
QIODevice::NotOpen 0x0000 The device is not open.
QIODevice::ReadOnly 0x0001 The device is open for reading.
QIODevice::WriteOnly 0x0002 The device is open for writing. Note that, for file-system subclasses (e.g. QFile), this mode implies Truncate unless combined with ReadOnly, Append or NewOnly.
QIODevice::ReadWrite ReadOnly | WriteOnly The device is open for reading and writing.
QIODevice::Append 0x0004 The device is opened in append mode so that all data is written to the end of the file.
QIODevice::Truncate 0x0008 If possible, the device is truncated before it is opened. All earlier contents of the device are lost.
QIODevice::Text 0x0010 When 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 0x0020 Any buffer in the device is bypassed.
QIODevice::NewOnly 0x0040 Fail if the file to be opened already exists. Create and open the file only if it does not exist. There is a guarantee from the operating system that you are the only one creating and opening the file. Note that this mode implies WriteOnly, and combining it with ReadWrite is allowed. This flag currently only affects QFile. Other classes might use this flag in the future, but until then using this flag with any classes other than QFile may result in undefined behavior. (since Qt 5.11)
QIODevice::ExistingOnly 0x0080 Fail if the file to be opened does not exist. This flag must be specified alongside ReadOnly, WriteOnly, or ReadWrite. Note that using this flag with ReadOnly alone is redundant, as ReadOnly already fails when the file does not exist. This flag currently only affects QFile. Other classes might use this flag in the future, but until then using this flag with any classes other than QFile may result in undefined behavior. (since Qt 5.11)
if(port.isOpen()){
	port.clear();
	port.close();
}

port.setPortName(name);
port.open(QIODevice);

port.setBaudRate();
port.setDataBits();
port.setFlowControl();
port.setParity();
port.setStopBits();

关闭串口

[virtual] void QIODevice::close()
First emits aboutToClose(), then closes the device and sets its OpenMode to NotOpen. The error string is also reset.

if (port.isOpen())
	port.close()

发送数据

// 接口
qint64 write(const char *data, qint64 maxSize)
qint64 write(const char *data)
qint64 write(const QByteArray &byteArray)

// Signals
void bytesWritten(qint64 bytes)

// 使用方法
QByteArray data;
port.write(data);

读取数据

// 接口
qint64 read(char *data, qint64 maxSize)
QByteArray read(qint64 maxSize)
QByteArray readAll()
qint64 readLine(char *data, qint64 maxSize)
QByteArray readLine(qint64 maxSize = 0)

// Signals
void readyRead()
// 利用信号异步处理
connect(&port, SIGNAL(readyRead()), this, SLOT(receiveInfo()));
void receiveInfo(){
	QByteArray data = port.readAll();
}

错误判断

signal:
void errorOccurred(QSerialPort::SerialPortError error);

function:
QSerialPort::SerialPortError error() const;
void clearError();

参考

https://doc.qt.io/archives/qt-5.12/qserialport.html
https://baike.baidu.com/item/串口通信/3775296

posted @ 2022-09-08 19:15  flxx  阅读(315)  评论(0编辑  收藏  举报