ChatGPT写QT读写串口数据的Demo

突发奇想,想使用ChatGPT试试能不能写一个读写串口数据的demo,以下为测试结果:

cpp 复制代码
#include <QCoreApplication>
#include <QtSerialPort/QSerialPort>
#include <QtSerialPort/QSerialPortInfo>
#include <QDebug>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    // 获取可用串口列表
    QList<QSerialPortInfo> serialPortList = QSerialPortInfo::availablePorts();
    if(serialPortList.isEmpty()) {
        qDebug() << "No serial ports found.";
        return 1;
    }

    // 选择第一个可用串口
    QSerialPort serialPort(serialPortList.at(0));
    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() << "Failed to open serial port.";
        return 1;
    }

    // 读取串口数据
    QObject::connect(&serialPort, &QSerialPort::readyRead, [&]() {
        QByteArray data = serialPort.readAll();
        qDebug() << "Received data:" << data;
    });

    // 写入数据到串口
    QByteArray dataToSend = "Hello, serial port!";
    serialPort.write(dataToSend);

    return a.exec();
}

这个示例代码会打开第一个可用的串口,设置串口的参数(波特率、数据位、校验位、停止位等),然后监听串口的数据读取事件,并将读取到的数据输出到控制台。同时,它也会向串口写入一条数据。你可以根据自己的需要修改和扩展这个示例代码。

相关推荐
博客18005 小时前
酷宝的使用方法,超好用的免费界面库,C++、MFC可用
c++·mfc·界面库·库来帮·酷宝
郝学胜_神的一滴6 小时前
CMake 026:属性体系精讲、四大作用域全解 & 实战代码落地
c++·cmake
众少成多积小致巨1 天前
JNI (Java Native Interface) 技术手册中文参考指南
android·java·c++
xcyxiner2 天前
DicomViewer (dcmtk读取dcm文件)5
qt
xcyxiner3 天前
DicomViewer (后台线程处理文件)4
qt
xcyxiner3 天前
DicomViewer (添加模型类)3
qt
xcyxiner4 天前
DicomViewer (目录调整) 2
qt
xcyxiner4 天前
dcmtk vtk vtk-dicom(gdcm) 编译(debug) v2
qt
clint4565 天前
C++进阶(1)——前景提要
c++
夜悊5 天前
C++代码示例:进制数简单生成工具
c++