QT5 串口收发实例代码

以下代码是自己测试门禁系统使用的

主要用到了串口的接收和发送

 开发环境:xp  QT5.1.1

串口:38400   N  8  1

自动检测可用串口

在xp上测试没问题

有些usb转串口会出现波特率不准的问题,CH340的usb转232使用完全正常

以下为收发的线程.h 和.cpp两个文件

最后附上转sacii显示的代码

如果要参考的话,源代码已上传:http://download.csdn.net/detail/liang890319/6463227

#ifndef MYTHREAD_H
#define MYTHREAD_H

#include <QThread>
#include <stdio.h>
#include <QtGlobal>

class MyThread : public QThread
{
    Q_OBJECT
public:
    QByteArray requestData;
    QByteArray TxData;
    MyThread();

    void setMessage(const QString &message);
    void setPortnum(const QString &num);
    void stop();
    void startCom();
    void changeTxState(bool stat);
    void changeRxState(bool stat);
    void changeComState(bool stat);

signals:
    void request(const QString &s);
    void comRecive();



protected:
    void run();

private:
    QString messageStr;
    QString portnum;
    volatile bool com_opened;
    volatile bool stopped;
    volatile bool tx_event;
    volatile bool rx_event;
};

#endif // MYTHREAD_H


 

#include "mythread.h"
#include <QtDebug>
//FOR RS232
#include <QtSerialPort/QSerialPort>
#include <QtSerialPort/QSerialPortInfo>

MyThread::MyThread()
{
   stopped=false;

}

void MyThread::run()
{
    QSerialPort *my_serialport= new QSerialPort;

    while(!stopped)
    {
        if(stopped&&com_opened)
        {
            my_serialport->close();
            com_opened=false;

        }
        if(!com_opened)
        {
            //open com
            qDebug() << "Brush:" <<"---open com port------";
            com_opened=true;
            my_serialport->setPortName(portnum);
            my_serialport->open(QIODevice::ReadWrite);
            my_serialport->setBaudRate(QSerialPort::Baud38400,QSerialPort::AllDirections);
            my_serialport->setDataBits(QSerialPort::Data8);
            my_serialport->setParity(QSerialPort::NoParity);
            my_serialport->setStopBits(QSerialPort::OneStop);
           // my_serialport->setStopBits(QSerialPort::TwoStop);
            my_serialport->setFlowControl(QSerialPort::NoFlowControl);
            com_opened=true;
        }
        if(this->com_opened&&this->tx_event)
        {
                this->tx_event=false;
                my_serialport->clear(QSerialPort::AllDirections);
                qDebug() << "Brush:" <<"send data to com2"<<this->TxData.length();
                qDebug() << "arr size:" <<this->TxData.length();
               my_serialport->write(this->TxData);
              if (my_serialport->waitForBytesWritten(5))
              {
                qDebug() << "Brush:" <<"send data success";
                if (my_serialport->waitForReadyRead(1500))  //1s
                {
                    requestData = my_serialport->readAll();
                    while (my_serialport->waitForReadyRead(15))
                    requestData += my_serialport->readAll();
                    emit(this->comRecive());
                }else
                {
                        qDebug() << "Brush:" <<"wait return time out";
                }
              }else
              {
                  qDebug() << "Brush:" <<"send time out";
              }
        }
    if (my_serialport->waitForReadyRead(5))  //50ms
    {
        while (my_serialport->waitForReadyRead(5))
        this->msleep(20);
        requestData = my_serialport->readAll();
        emit(this->comRecive());
    }
    if(stopped&&com_opened)
    {
        my_serialport->close();
        com_opened=false;
    }
    }
}

void MyThread::stop()
{
   stopped=true;

}
void MyThread::startCom()
{
   stopped=false;

}
void MyThread::changeComState(bool stat)
 {
        com_opened=stat;
}
void MyThread::setMessage(const QString &message)
{
   messageStr = message;

}
void MyThread::setPortnum(const QString &num)
{
    portnum=num;

}
void MyThread:: changeTxState(bool stat)
{
        tx_event=stat;
}
void MyThread:: changeRxState(bool stat)
{
         rx_event=stat;
}


 

显示部分 比如收到0xff  在text框显示 FF

void MainWindow::displayRxData()
{
    QString str;
    char tmp[100];
    char *buf;
    char var;
    QDateTime *datatime=new QDateTime(QDateTime::currentDateTime());
    if(threadA.requestData.size()>0)
   {
        str="收到数据: ";
        str+=datatime->time().toString();
        ui->textEdit_rx->append(str);
        str.clear();

        buf=threadA.requestData.data();
        if(buf[3]==0x01) ui->textEdit_tx->append("加卡成功!");
        if(buf[3]==0x02) ui->textEdit_tx->append("删卡成功!");
        if(buf[3]==0x03) ui->textEdit_tx->append("开门成功!");
        if(buf[3]==0x04) ui->textEdit_tx->append("关门成功!");
        qDebug() << "receive num:" <<threadA.requestData.size();
        for(var=0;var<threadA.requestData.size();var++)
        {
            ::snprintf(tmp,100, "%02X", (unsigned char)(*buf));
            buf++;
            str+=QString::fromUtf8(tmp);
            str+=" ";
        }
        ui->textEdit_rx->append(str);
    }
    threadA.requestData.clear();
}


 

原文地址:https://www.cnblogs.com/pangblog/p/3395230.html