1.编译环境:Qt 5.8.0
2.实现方法:使用Qt中的QSerialPort类。
3.头文件:
#include <QSerialPort>
pro文件中加入:
QT += serialport
4.具体实现:
初始化:在Mainwindowli 创建QSerialPort类并进行相关的信号槽连接:
serial = new QSerialPort(this); //创建QSerialPort类
connect(serial, static_cast<void (QSerialPort::*)(QSerialPort::SerialPortError)>(&QSerialPort::error),
this, &MainWindow::handleError); //连接槽,串口出现问题连接到错误处理函数
connect(serial, &QSerialPort::readyRead, this, &MainWindow::readData); //将串口接到数据连接到自定义的接收数据函数
串口配置与打开串口函数:
//! [4]
void MainWindow::openSerialPort()
{
SettingsDialog::Settings p = settings->settings(); //之前定义一个QSetting类settings用来保存串口的配置,下面用QSerialPort::set... 设置串口的属性
serial->setPortName(p.name