从 Arduino 读取时错误的先前值

Wrong previous value when reading from Arduino

我正在使用QT从连接到Arduino板的光敏电阻读取值,我成功读取了该值并发出了它,如下所示:

void Dialog::handleReadyRead(){
    QString temp;
    temp = serial.readAll();
    serialBuffer.append(temp);
    int serPos;
    double tempValue;
    double previousValue = tempValue;
    while ((serPos = serialBuffer.indexOf('\n')) >= 0)
    {
        bool ok;
        previousValue = tempValue;
        tempValue =     QString::fromLatin1(serialBuffer.left(serPos)).toDouble(&ok);
        if (ok){
            emit newData(tempValue, previousValue);
        }
        serialBuffer = serialBuffer.mid(serPos+1);
    }
}

但是,出于某种原因,我需要获取以前的值。当我执行 previousValue = tempValue 时,它会打印出一些奇怪的值(有时它确实是以前的值,但大多数时候它只是打印出 0 或一些非常接近 0 的数字)。我想知道这里发生了什么,我该如何解决?

示例错误输出可能如下:

399
399
399
399
399
399
399
399
399
399
399
399
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1.49189e-154
1.49189e-154
0
0
0

399 是正确的值,而全 0 则不是。

我假设每当 (true != ok) 您的值无效时。问题可能就在那里,你保留那个值,而你应该丢弃它。

你呢

bool ok;
double parsed = QString::fromLatin1(serialBuffer.left(serPos)).toDouble(&ok);
if (ok) {
    previousValue = tempValue;
    tempValue = parsed;
    emit newData(parsed, previousValue);      
    }

在该示例中,将 tempValue 重命名为 currValue 可能是相关的。

试试这个

double tempValue = 0;
double previousValue = 0;

while ((serPos = serialBuffer.indexOf('\n')) >= 0)
{
    tempValue = QString::fromLatin1(serialBuffer.left(serPos)).toDouble(&ok);

    if (previousValue != 0 && tempValue != 0){
        emit newData(tempValue, previousValue);
    }

    previousValue = tempValue
    serialBuffer = serialBuffer.mid(serPos+1);
}