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

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

相关推荐
kyle~1 小时前
C# --- 反射
开发语言·c#
soso19681 小时前
低功耗设计与BMS开发指南
c语言·开发语言·汇编
Risehuxyc2 小时前
来自PHP项目devnexen的回信
开发语言·php
FRing033 小时前
vue2干货总结10(json-server、vant-ui、postcss插件、axios二次封装、图形验证码、toast轻提示)
开发语言·前端·vue.js·ui·json·vue2·postcss
kyle~3 小时前
因子图优化(Factor Graph Optimization)
c++·算法·机器人·传感器
我是大猴子3 小时前
分析sss
开发语言
geats人山人海3 小时前
现代c++4.1
java·开发语言·c++
布莱克6054 小时前
Swift 字符串详解:从基础用法到性能与最佳实践
服务器·开发语言·ssh·字符串·swift
饿了吃洗衣凝珠5 小时前
SELinux
服务器·开发语言·php
蜗牛一步步往上爬5 小时前
第四章 更多的bash shell命令
linux·开发语言·bash