【问题标题】:Parsing G-code with arduino from an sd card使用 arduino 从 sd 卡解析 G 代码
【发布时间】:2020-05-03 17:05:40
【问题描述】:

正如标题所示,我正在使用以下函数来读取 SD 卡上存在的一些 g-code 文件的参数:

long parseParameters(String data, char* c){
    int offset = data.indexOf(c);
    int offset1 = data.lastIndexOf(" ", offset + 1);
    return offset1 > 0 ? data.substring(offset + 1, offset + offset1 + 1).toInt() : data.substring(offset + 1).toInt();
}

void setup(){
    Serial.begin(9600);
    String q = "P3 S255"; // input
    Serial.println(parseParameters(p, "S")); // output
}

void loop(){

}

直到今天,在试图读取字符串P3 S255S的值时出现了一个小bug:

INPUT -> OUTPUT
P3 S255 -> 25 (wrong)
A20 P3 S255 -> 255 (Correct)
S255 -> 255 (Correct)

为什么?然而代码对我来说似乎是正确的......我哪里出错了?

提前感谢大家.. :)

【问题讨论】:

  • 这是一个很好解决的问题,并且在您之前解决得相当严格。查找专为 Arduino 平台设计的 Marlin 或其他固件。它都是开源的,可以为您提供线索或说服您停止重新发明轮子。
  • 我理解您的观点,但有时,在尝试编程语言时,即使能够重新发明轮子也不会让人感到满意.. :)

标签: c++ arduino arduino-uno arduino-c++


【解决方案1】:

这就是解释:

int offset = data.indexOf(c); //in your example S

 "P3 S255";
     ^
  offset = 3

然后您解析偏移量1,但在偏移量之后取另一个参数,即“”-但偏移量+1的字符串中没有“”,请参阅上面的索引位置,所以它返回-1,为什么?

 myString.lastIndexOf(val, from) The index of val within the String, or -1 if not found. But we find something:

offset = 3;
offset1 = 2 ==> offset1 > 0 ==> data.substring(offset + 1, offset + offset1 + 1).toInt()

导致

 data.substring(3 + 1, 3 + 2 + 1).toInt()
      "P3 S*4*25*6*5"; which results to 25 as you already know

to(可选):结束子字符串before的索引。

所以你有正确的 S 在开始通过更改为

data.substring(offset + 1, offset + 1 + offset1 + 1).toInt() 

说明:您从 offset + 1 开始,这在 from 和 to 中必须相等(= 您的计算起点相同)

【讨论】:

  • 哇!多么详细的解释!谢谢.. :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-02
  • 1970-01-01
相关资源
最近更新 更多