QTシリアル通信

2647 ワード

Qt Qserialを使用して読み取りを完了
 
 
コードの一部は次のとおりです.
 
    serial = new QSerialPort(this);    //  QSerialPort 
    connect(serial, static_cast(&QSerialPort::error), this, &SerialManager::handleError);    //   ,               
    connect(serial, &QSerialPort::readyRead, this, &SerialManager::readData);   //                    

 
 
 
bool SerialManager::openSerialPort(QString portName , int BaudRate)
{
    closeSerialPort();
 
    serial->setPortName(portName);
    serial->setBaudRate(BaudRate);
    serial->setDataBits(QSerialPort::Data8);
    serial->setParity(QSerialPort::NoParity);
    serial->setStopBits(QSerialPort::OneStop);
    serial->setFlowControl(QSerialPort::NoFlowControl);
 
    //           
    if (serial->open(QIODevice::ReadWrite))
    {
        qDebug() << "open success";
    }
    else
    {
        qDebug() << "open failed";
        return false;
    }
    return true;
}

 
 
 
 
void SerialManager::readData()
{
   QString tmpStr = serial->readAll();
   tmpStr = tmpStr.trimmed().replace(" ","");
 
   if(strBuffer.length() < SerialMsgMaxLength)
   {
        strBuffer+=tmpStr;
        if(strBuffer.length() == SerialMsgMaxLength)
        {
            emit SgnRecvedMsg(strBuffer);
            strBuffer.clear();
        }
        else if(strBuffer.length() > SerialMsgMaxLength)
        {
            strBuffer.clear();
        }
   }
}