Arduino 子串不起作用

Arduino substring doesn't work

我有一个静态方法可以搜索(和 returns)到 String msg 中 TAG

之间的值

这是代码函数:

static String genericCutterMessage(String TAG, String msg){
    Serial.print("a-----");
    Serial.println(msg);
    Serial.print("b-----");
    Serial.println(TAG);
    if(msg.indexOf(TAG) >= 0){
        Serial.print("msg ");
        Serial.println(msg);
        int startTx = msg.indexOf(TAG)+3;
        int endTx = msg.indexOf(TAG,startTx)-2;
        Serial.print("startTx ");
        Serial.println(startTx);
        Serial.print("endTx ");
        Serial.println(endTx);
        String newMsg = msg.substring(startTx,endTx);
        Serial.print("d-----");
        Serial.println(newMsg);
        Serial.println("END");
        Serial.println(newMsg.length());
        return newMsg;
    } else {
        Serial.println("d-----TAG NOT FOUND");
        return "";
    }
}

这是输出

a-----[HS][TS]5132[/TS][TO]5000[/TO][/HS]
b-----HS
msg [HS][TS]5132[/TS][TO]5000[/TO][/HS]
startTx 4
endTx 30
d-----
END
0
fake -_-'....go on!  <-- print out of genericCutterMessage

在那种情况下我想要 return HS 标签之间的字符串,所以我的预期输出是

[TS]5132[/TS][TO]5000[/TO]

但我不知道为什么我会收到一个空字符串。

为了了解子字符串的工作原理,我刚刚按照 Arduino 官方网站上的教程进行操作

http://www.arduino.cc/en/Tutorial/StringSubstring

我不是 C++ 和 Arduino 方面的专家,但这看起来像是冲洗或缓冲问题,不是吗?

有什么想法吗?

您的代码是正确的,这不应该发生。这迫使您考虑可能失败的意外方式。我真的只能想到一个候选人的不幸事件,你的 Arduino 是 运行 内存不足。它很少,例如 Uno 只有 2 KB。填满它并不需要大量的字符串咀嚼。

这不是一个顺利的报告。我所能做的就是将您指向相关的 company page。引用:

If you run out of SRAM, your program may fail in unexpected ways; it will appear to upload successfully, but not run, or run strangely. To check if this is happening, you can try commenting out or shortening the strings or other data structures in your sketch (without changing the code). If it then runs successfully, you're probably running out of SRAM. There are a few things you can do to address this problem:

  • If your sketch talks to a program running on a (desktop/laptop) computer, you can try shifting data or calculations to the computer, reducing the load on the Arduino.
  • If you have lookup tables or other large arrays, use the smallest data type necessary to store the values you need; for example, an int takes up two bytes, while a byte uses only one (but can store a smaller range of values).
  • If you don't need to modify the strings or data while your sketch is running, you can store them in flash (program) memory instead of SRAM; to do this, use the PROGMEM keyword.

这对您的具体情况不是很有帮助,您必须查看该计划的其余部分以供候选人参考。或者升级您的硬件,StackExchange 为 Arduino 爱好者提供了 dedicated site,这无疑是获得建议的最佳场所。