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();
}

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

相关推荐
saltymilk14 小时前
C++ 模板参数推导问题小记(模板类的模板构造函数)
c++·模板元编程
感哥15 小时前
C++ lambda 匿名函数
c++
沐怡旸21 小时前
【底层机制】std::unique_ptr 解决的痛点?是什么?如何实现?怎么正确使用?
c++·面试
感哥21 小时前
C++ 内存管理
c++
博笙困了1 天前
AcWing学习——双指针算法
c++·算法
感哥1 天前
C++ 指针和引用
c++
感哥2 天前
C++ 多态
c++
沐怡旸2 天前
【底层机制】std::string 解决的痛点?是什么?怎么实现的?怎么正确用?
c++·面试
River4162 天前
Javer 学 c++(十三):引用篇
c++·后端
感哥2 天前
C++ std::set
c++