Qt串口有时会丢失最后一个字节

时间:2016-05-12 15:12:40

标签: c++ qt

我正在用Qt和arduino制作RPM计数器GUI,我正在使用冷却乐趣来获取RPM值。 我正在使用串口从arduino读取值,但有时我会错过我在Qt GUI中打印的值的最后一个字节,但我在arduino串行监视器中没有相同的问题。以下是Qt的代码:

void ArduinoRpm::serialReciver()
{

    QString input_converter;
    std::string to_file_string;

    int sizeFromInput = 0;
    char *dataBuffer;

    //get the port size depending on bytes available to read
    int bufferSize = serial->bytesAvailable();
    //int bufferSize = serial->bytesAvailable();

    //dataBuffer, get the data from serial port, bufferSize + 1 for the newline
    dataBuffer = new char[bufferSize + 2];

    //flush the port before read


    //This function reads a line of ASCII characters from the device, up to a maximum of
    //maxSize - 1 bytes, stores the characters in dataBuffer, and returns the number of bytes
    //read. if a line could not be read but no error ocurred, this function returns 0. if an
    //error occurs, this function returns the length of what could read or -1 if nothing was read.
    //bufferSize is the maxsize readline can read.

    sizeFromInput = serial->readLine(dataBuffer, bufferSize);

    //to_file_string, to write data in file
    to_file_string = dataBuffer;
    input_converter = QString::fromStdString(to_file_string);


    if ((sizeFromInput >= 1) && (input_converter.toInt() <= 9999)) {
        if(input_converter.toInt() > 10) {
            ui->lcdNumber->display(input_converter);
            rpmNeedle->setCurrentValue(input_converter.toInt());
            input_file << to_file_string << std::endl;
        }

    }

    delete dataBuffer;
    bufferSize = 0;
    serial->flush();

}

 void ArduinoRpm::SerialInitializer()
{
    serial = new QSerialPort(this);
    serial->setPortName(serialPortValue); //COM-port your Arduino is connected to
    serial->open(QIODevice::ReadWrite);
    serial->setBaudRate(QSerialPort::Baud9600); //must be the same as your arduino-baudrate
    serial->setDataBits(QSerialPort::Data8);
    serial->setParity(QSerialPort::NoParity);
    serial->setStopBits(QSerialPort::OneStop);
    serial->setFlowControl(QSerialPort::NoFlowControl);
}

例如

27
1621
1621
1627
1627
1627
1627
1627
1627
1627
1627
1627
1627
1627
1627
1627
1621
1616
1616
1605
1605
1599
1594
1588
158
1583
158
1578
1578
1572
1572
1572

它应该一直读取4位数,但有时会丢失最后一位数字。 对此有何解决方案?

1 个答案:

答案 0 :(得分:0)

你的功能应该是这样的:

void ArduinoRpm::serialReciver()
{
    char dataBuffer[6];

    if(!serial->canReadLine()) //if there isn't a whole line available
        return; //return from this call (wait for the next readyRead() signal)
    serial->readLine(dataBuffer, 6)

    /* do whatever you want with dataBuffer here */

    if(serial->bytesAvailable() > 0) //if there are still unread bytes
        QMetaObject::invokeMethod(this, "serialReciver", Qt::QueuedConnection); //call function again as if readyRead() signal was emitted
}

P.S这个答案假定输入保证总是这样:4个数字字符然后换行,然后是4个数字字符,然后再换行,等等。 。因此,如果它不遵循这种模式,那么这将导致未定义的行为。

P.S我没有在 serialReciver 中解决您的拼写错误。