《Qt串口通信》--实时显示接收的数据

为了能在接收到串口发送的数据便即时显示在文本框中,首先要在连接串口时绑定信号和槽,即将serialport的signal(QIODevice::readyRead)与this的槽函数SePort::ReadCom连接在一起,这样,一旦serialport的准备读取数据信号过来时,就会调用自定义的ReadCom函数,把缓存区的数据读取到私有成员变量m_bReceiveData中。为了能在界面上显示,我们将暴露一个接口GetUsePort()以便于上层函数获得使用的串口serialport,然后自定义函数ShowData()将读取的数据实时显示在串口中,核心代码如下:

void SerialPort::ConnectPort(QString portName)
{
    ClearConnection();

    if(portName.isEmpty())
        throw(SerialPortException(QString::fromLocal8Bit("未找到可用串口号,请检查串口名是否正确")));

    //尝试打开三次
    QSerialPort *tmpPort = new QSerialPort(portName);
    bool isOpen=false;
    for(int i=0;i<3;i++)
    {
        if(tmpPort->open(QIODevice::ReadWrite))
        {
            isOpen = true;
            break;
        }
        else
        {
            qDebug()<<"Failed";
            Wait(1.0);
        }
    }
    if(isOpen == false)
    {
        throw(SerialPortException(QString::fromLocal8Bit("未能正确打开串口,请检查串口连接是否正确")));
        delete tmpPort;
        tmpPort = NULL;
    }

    m_pPort = tmpPort;

    //当有数据时(readyRead),调用ReadCom函数
    connect(m_pPort,&QSerialPort::readyRead,this,&SerialPort::ReadCom);
}


QSerialPort *DP700::GetUseSePort()
{
    return m_pSePort->GetSerialPort();
}

void MainWindow::ShowReceiveData()
{
    ui->receive_textEdit->setText(m_pDp700->ReceiveData());
}

connect(m_pDp700->GetUseSePort(),&QIODevice::readyRead,this,&MainWindow::ShowReceiveData);



你可能感兴趣的:(串口通信)