首页 > 解决方案 > 串口过滤返回

问题描述

我的 Arduino Mega 上有一个 CO2 传感器,有时当我读取 CO2 测量值时,传感器会随机返回一个“?”。问号导致我的程序崩溃并返回“输入字符串的格式不正确”。

我没有尝试过任何事情,因为我不知道哪种方法最适合这个。CO2 传感器以“Z 00000”的形式返回测量值,但是当出现此问号时,它显示返回的只是一个“\n”。目前,我的程序只读取 Z 之后的 5 位数字。

if (returnString != "")
{
    val = Convert.ToDouble(returnString.Substring(returnString.LastIndexOf('Z')+ 1));
}

我期望返回的是 Z 之后的数字,它可以工作,但我经常会得到一个随机行返回,这会使一切崩溃。

标签: visual-studioarduino

解决方案


根据C# 文档,只要输入字符串无效,ToDouble 方法就会抛出 FormatException。您应该捕获异常以避免进一步的问题。

try {
   val = Convert.ToDouble(returnString.Substring(returnString.LastIndexOf('Z')+ 1));
}
catch(FormatException e) {
   //If you want to do anything in case of an error
   //Otherwise you can leave it blank
}

另外,我建议您使用某种状态机来解析您的数据,这可能会丢弃所有无效字符。像这样的东西:

bool z_received = false;
int digits = 0;
int value = 0;

//Called whenever you receive a byte from the serial port
void onCharacter(char input) {
    if(input == 'Z') {
        z_received = true;
    }
    else if(z_received && input <= '9' && input >= '0') {
        value *= 10;
        value += (input - '0');
        digits++;
        if(digits == 5) {
            onData(value);
            value = 0;
            z_received = false;
            digits = 0;
        }
    }
    else {
        value = 0;
        z_received = false;
        digits = 0;
    }
}

void onData(int data) {
    //do something with the data
}

这只是一个模型,如果您可以将 COM 端口的字节流定向到 onCharacter 函数,则应该适用于您的情况。


推荐阅读