- Qt5 提供了对串口通信的支持,主要通过 QSerialPort 和 QSerialPortInfo 类来实现。
引入相关模块
- 在使用 Qt5 的串口功能之前,需要在项目配置文件(.pro 文件)中添加串口模块:
QT += serialport
主要类介绍
QSerialPort
- QSerialPort 类用于串口通信,提供了打开、关闭、读取、写入串口数据的功能。
- 常用方法:
open(QIODevice::OpenMode mode):打开串口。
close():关闭串口。
setPortName(const QString &name):设置串口名称(如 "COM1" 或 "/dev/ttyS0")。
setBaudRate(qint32 baudRate):设置波特率。
setDataBits(QSerialPort::DataBits dataBits):设置数据位。
setParity(QSerialPort::Parity parity):设置校验位。
setStopBits(QSerialPort::StopBits stopBits):设置停止位。
setFlowControl(QSerialPort::FlowControl flowControl):设置流控制。
write(const QByteArray &data):向串口写入数据。
readAll():读取串口所有可用数据。
readyRead() 信号:当有数据可读时触发。
QSerialPortInfo
-
QSerialPortInfo 类用于获取系统中可用的串口信息。
-
常用方法:
availablePorts():获取系统中所有可用的串口。
portName():获取串口名称。
description():获取串口描述。
manufacturer():获取串口制造商信息。
serialNumber():获取串口序列号。
获取可用串口
#include <QSerialPortInfo>
#include <QDebug>
QList<QSerialPortInfo> ports = QSerialPortInfo::availablePorts();
foreach (const QSerialPortInfo &port, ports) {
qDebug() << "Port:" << port.portName();
qDebug() << "Description:" << port.description();
qDebug() << "Manufacturer:" << port.manufacturer();
}
创建 QSerialPort 对象
- QSerialPort 对象通常以指针形式创建,因为这样可以更好地管理对象的生命周期,并且在需要时可以动态地创建和销毁串口对象。
#include <QSerialPort>
#include <QSerialPortInfo>
QSerialPort *serialPort = new QSerialPort(this);
配置串口参数
- 在打开串口之前,需要配置串口的参数,如波特率、数据位、停止位、校验位等。
serialPort->setPortName("COM1"); // 设置串口名称,例如 "COM1" 或 "/dev/ttyUSB0"
serialPort->setBaudRate(QSerialPort::Baud9600); // 设置波特率
serialPort->setDataBits(QSerialPort::Data8); // 设置数据位
serialPort->setParity(QSerialPort::NoParity); // 设置校验位
serialPort->setStopBits(QSerialPort::OneStop); // 设置停止位
serialPort->setFlowControl(QSerialPort::NoFlowControl); // 设置流控制
打开串口
- 配置好串口参数后,可以尝试打开串口:
if (serialPort->open(QIODevice::ReadWrite)) {
// 串口打开成功
qDebug() << "Serial port opened successfully.";
} else {
// 串口打开失败
qDebug() << "Failed to open serial port:" << serialPort->errorString();
}
读取和写入数据
- 串口打开后,可以通过 read() 和 write() 方法进行数据的读取和写入。
读取数据
- 可以通过 readyRead() 信号来监听是否有数据可读,并在槽函数中读取数据:
connect(serialPort, &QSerialPort::readyRead, this, &MyClass::readData);
void MyClass::readData() {
QByteArray data = serialPort->readAll();
qDebug() << "Received data:" << data;
}
写入数据
- 可以通过 write() 方法向串口写入数据:
QByteArray data = "Hello, Serial Port!";
serialPort->write(data);
关闭串口
- 当不再需要使用串口时,应该关闭串口以释放资源:
serialPort->close();
错误处理
- 在串口通信过程中,可能会遇到各种错误,如打开失败、读写错误等。可以通过 errorOccurred() 信号来捕获错误并进行处理:
connect(serialPort, &QSerialPort::errorOccurred, this, &MyClass::handleError);
void MyClass::handleError(QSerialPort::SerialPortError error) {
if (error == QSerialPort::ResourceError) {
qDebug() << "Critical error:" << serialPort->errorString();
serialPort->close();
}
}
释放资源
- 如果 QSerialPort 对象是通过 new 创建的,记得在不再需要时释放资源:
delete serialPort;
示例代码
- 以下是一个简单的串口通信示例:
#include <QCoreApplication>
#include <QSerialPort>
#include <QSerialPortInfo>
#include <QDebug>
class SerialPortHandler : public QObject {
Q_OBJECT
public:
SerialPortHandler(QObject *parent = nullptr) : QObject(parent) {
serialPort = new QSerialPort(this);
connect(serialPort, &QSerialPort::readyRead, this, &SerialPortHandler::readData);
connect(serialPort, &QSerialPort::errorOccurred, this, &SerialPortHandler::handleError);
serialPort->setPortName("COM1");
serialPort->setBaudRate(QSerialPort::Baud9600);
serialPort->setDataBits(QSerialPort::Data8);
serialPort->setParity(QSerialPort::NoParity);
serialPort->setStopBits(QSerialPort::OneStop);
serialPort->setFlowControl(QSerialPort::NoFlowControl);
if (serialPort->open(QIODevice::ReadWrite)) {
qDebug() << "Serial port opened successfully.";
} else {
qDebug() << "Failed to open serial port:" << serialPort->errorString();
}
}
~SerialPortHandler() {
serialPort->close();
delete serialPort;
}
private slots:
void readData() {
QByteArray data = serialPort->readAll();
qDebug() << "Received data:" << data;
}
void handleError(QSerialPort::SerialPortError error) {
if (error == QSerialPort::ResourceError) {
qDebug() << "Critical error:" << serialPort->errorString();
serialPort->close();
}
}
private:
QSerialPort *serialPort;
};
int main(int argc, char *argv[]) {
QCoreApplication a(argc, argv);
SerialPortHandler handler;
return a.exec();
}
#include "main.moc"