Qt 串口通信(QSerialPort) 读取蓝牙笔的报文数据

(1) 开发环境:qt5.5.1和VS2010
(2) 使用的时候在 pro 添加这句导入模块 QT += serialport
(3) //搜索串口,并添加到选项上供使用者选择
    foreach(const QSerialPortInfo &Info,QSerialPortInfo ::availablePorts())
    {
        QSerialPort CurrentPort;
        CurrentPort.setPort(Info);
        if(CurrentPort.open(QIODevice::ReadWrite))
        {
            this->ui->BlueToothPortComboBox->addItem(CurrentPort.portName());//插入串口的名字
            CurrentPort.close();   //先开再关,把串口名称先导入
        }

    }
(4) 连接串口
    void MainWindow::on_pushButton_connect_clicked()
    {
        CurrentPort = new QSerialPort;
        CurrentPort->setPortName(this->ui->BlueToothPortComboBox->currentText());//设置串口名
        //设置波特率
        switch (this->ui->BaudRateComBox->currentIndex())
        {
        case 0: this->ui->textEdit_show->append("Baud:115200");
            CurrentPort->setBaudRate(QSerialPort::Baud115200,QSerialPort::AllDirections); break;
        case 1: this->ui->textEdit_show->append("Baud:9600");
            CurrentPort->setBaudRate(QSerialPort::Baud9600,QSerialPort::AllDirections); break;
        default: break;
        }

        //设置数据位数
        switch(this->ui->DateRateComBox->currentIndex())
        {
        case 0: this->ui->textEdit_show->append("Data:5");
            CurrentPort->setDataBits(QSerialPort::Data5); break;
        case 1: this->ui->textEdit_show->append("Data:6");
            CurrentPort->setDataBits(QSerialPort::Data6); break;
        case 2: this->ui->textEdit_show->append("Data:7");
            CurrentPort->setDataBits(QSerialPort::Data7); break;
        case 3: this->ui->textEdit_show->append("Data:8");
            CurrentPort->setDataBits(QSerialPort::Data8); break;
        default: break;
        }
        //设置奇偶校验
        switch(this->ui->ParityComBox->currentIndex())
        {
        case 1:this->ui->textEdit_show->append("Parity: off");
            CurrentPort->setParity(QSerialPort::NoParity); break;
        default: break;
        }
        switch(this->ui->StopBitsComBox->currentIndex())   //设置停止位
        {
        case 0: this->ui->textEdit_show->append("StopBits:1");
            CurrentPort->setStopBits(QSerialPort::OneStop); break;
        case 1: this->ui->textEdit_show->append("StopBits:2");
            CurrentPort->setStopBits(QSerialPort::TwoStop); break;
        default: break;
        }
        CurrentPort->setFlowControl(QSerialPort::NoFlowControl);  //设置流控制

        CurrentPort->open(QIODevice::ReadWrite);//打开串口

        if(CurrentPort->isOpen())
        {
            this->ui->textEdit_show->append("Succeesfully open the Port ");
            //关闭设置菜单使能
            this->ui->BlueToothPortComboBox->setEnabled(false);
            this->ui->BaudRateComBox->setEnabled(false);
            this->ui->DateRateComBox->setEnabled(false);
            this->ui->ParityComBox->setEnabled(false);
            this->ui->StopBitsComBox->setEnabled(false);


        }
        else
        {
            this->ui->textEdit_show->append("Defeatly open the port");
        }

        //连接信号槽
        QObject::connect(CurrentPort, &QSerialPort::readyRead, this, &MainWindow::Read_Data);

    }

(5) 读取数据
    void MainWindow::Read_Data()//读取接收到的数据
    {
        QByteArray buf;
        buf = CurrentPort->readAll();//Qbytearray类提供一个字节数组,buf这里应该是缓冲数据的功能

        QString str =   QString::fromStdString(buf.toStdString());

        str = QString::fromStdString((buf.toHex()).toStdString());

    }
(6) 发送数据
    void MainWindow::sendInfo(const QString &info)
    {
    
        QByteArray sendBuf;
        if (info.contains(" "))
        {
            info.replace(QString(" "),QString(""));//我这里是把空格去掉,根据你们定的协议来
        }
        
        qDebug()<<"Write to serial: "<<info;
        convertStringToHex(info, sendBuf); //把QString 转换 为 hex
        
        CurrentPort->write(sendBuf);////这句是真正的给单片机发数据 用到的是QIODevice::write 具体可以看文档

    }
    
    void MainWindow::convertStringToHex(const QString &str, QByteArray &byteData)
    {
        int hexdata,lowhexdata;
        int hexdatalen = 0;
        int len = str.length();
        byteData.resize(len/2);
        char lstr,hstr;
        for(int i=0; i<len; )
        {
            //char lstr,
            hstr=str[i].toLatin1();
            if(hstr == ' ')
            {
                i++;
                continue;
            }
            i++;
            if(i >= len)
                break;
            lstr = str[i].toLatin1();
            hexdata = convertCharToHex(hstr);
            lowhexdata = convertCharToHex(lstr);
            if((hexdata == 16) || (lowhexdata == 16))
                break;
            else
                hexdata = hexdata*16+lowhexdata;
            i++;
            byteData[hexdatalen] = (char)hexdata;
            hexdatalen++;
        }
        byteData.resize(hexdatalen);
    }
    
    char MainWindow::convertCharToHex(char ch)
    {
        if((ch >= '0') && (ch <= '9'))
             return ch-0x30;
         else if((ch >= 'A') && (ch <= 'F'))
             return ch-'A'+10;
         else if((ch >= 'a') && (ch <= 'f'))
             return ch-'a'+10;
         else return (-1);
    }


(7) 关闭串口
    if (CurrentPort->isOpen())
    {
        CurrentPort->close();
    }
    delete CurrentPort;

猜你喜欢

转载自blog.csdn.net/qq_14874791/article/details/107115554
今日推荐