Qt5 串口读写

2021-05-18  本文已影响0人  有事没事扯扯淡

还是直接上干货!!

1. 遍历所有可用串口

#include<QSerialPort>
#include <QtSerialPort/QSerialPortInfo>
#include <QTimer>
#include <string>
#include <fstream>
#include "SaveAsGUI.h"

...
QSerialPort *serial_port_locate;
QStringList serialPortName;

serial_port_locate = new QSerialPort() ;

if (serial_port_locate->isOpen())   //如果串口已经打开了 先给他关闭了
{
    serial_port_locate->clear();
    serial_port_locate->close();
}
foreach(const QSerialPortInfo &info, QSerialPortInfo::availablePorts())
{
    serialPortName << info.portName();
    ui.comboBox_serialPort->addItem(info.portName());
    ui.comboBox_serialPort_measure->addItem(info.portName());
}

if (serialPortName.isEmpty())
{
    //QMessageBox::critical(0, "critical message", "Do you want to process?", QMessageBox::Ok | QMessageBox::Default, QMessageBox::Cancel | QMessageBox::Escape, 0);
    QMessageBox::warning(NULL, "Warning", "There is no COM! ", QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);
}

...

2. 初始化串口参数

void uart_open()
{
    //-> setting serial port
    serial_port_locate->setPortName(ui.comboBox_serialPort->currentText());   //    选取串口  
    if (!serial_port_locate->open(QIODevice::ReadWrite))                                       //打开串口  
    {
        QMessageBox::critical(NULL, "Error", "Cann't open COM port!", QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);
        return;
    }
    serial_port_locate->setBaudRate(QSerialPort::Baud38400);                            //设置波特率  
    serial_port_locate->setDataBits(QSerialPort::Data8);                                     //设置数据位数  
    serial_port_locate->setParity(QSerialPort::NoParity);                                      //设置奇偶校验   
    serial_port_locate->setStopBits(QSerialPort::OneStop);                                 //设置停止位 
    serial_port_locate->setFlowControl(QSerialPort::NoFlowControl);                //设置流控制  

    connect(serial_port_locate, SIGNAL(readyRead()), this, SLOT(get_data()));
    serial_port_locate->waitForReadyRead();
    //ui.light_locate->setIcon(icon_light_on);
}

3. 发送数据

std::string order = "*meas:dark 10 10 " + to_string(OUTPUT_MODE) + "\r";
serial_port_measure->write(order.c_str());
serial_port_measure->waitForReadyRead();

4. 接受数据

4.1 一次性读取

QByteArray readBuf;
readBuf = serial_port_locate->readAll();

4.2 阻塞 / 监听接收数据

此处不上源码了 给出官方链接,可以看看examples官方实现,直接抄就行~~

上一篇 下一篇

猜你喜欢

热点阅读