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

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

相关推荐
Aaswk14 分钟前
Java Lambda 表达式与流处理
java·开发语言·python
万邦科技Lafite32 分钟前
京东item_get接口实战案例:实时商品价格监控全流程解析
java·开发语言·数据库·python·开放api·淘宝开放平台
liuhuizuikeai1 小时前
可视化门禁---Linux/Qt+SqLite篇
linux·运维·qt
王老师青少年编程1 小时前
csp信奥赛C++高频考点专项训练之字符串 --【子串查找】:[NOIP 2009 提高组] 潜伏者
c++·字符串·csp·高频考点·信奥赛·子串查找·潜伏者
Cyber4K2 小时前
【Python专项】进阶语法-系统资源监控与数据采集(1)
开发语言·python·php
初願致夕霞2 小时前
基于系统调用的Linux网络编程——UDP与TCP
linux·网络·c++·tcp/ip·udp
Le_ee2 小时前
ctfweb:php/php短标签/.haccess+图片马/XXE
开发语言·前端·php
yong99903 小时前
MATLAB读取高光谱图像
开发语言·matlab
2zcode3 小时前
基于MATLAB的肝病风险评估与分期分析系统设计与实现
开发语言·matlab
小小de风呀3 小时前
de风——【从零开始学C++】(五):内存管理
开发语言·c++