繁体   English   中英

处理bufferUntil()方法仅适用于'\\ n'

[英]Processing bufferUntil() method only works with '\n'

TL,DR:设置为'\\ n'时,bufferUntil()和readStringUntil()可以正常工作,但会给其他字符带来麻烦。

将数据发送到pc的代码如下;

 Serial.print(rollF);
 Serial.print("/");
 Serial.println(pitchF);

加工的相关零件是;

myPort = new Serial(this, "COM3", 9600); // starts the serial communication
  myPort.bufferUntil('\n');

void serialEvent (Serial myPort) { 
  // reads the data from the Serial Port up to the character '\n' and puts it into the String variable "data".
  data = myPort.readStringUntil('\n');
  // if you got any bytes other than the linefeed:
  if (data != null) {
    data = trim(data);
    // split the string at "/"
    String items[] = split(data, '/');
    if (items.length > 1) {
      //--- Roll,Pitch in degrees
      roll = float(items[0]);
      pitch = float(items[1]);
    }
  }
}

来自我的传入数据的图片(来自arduino串行监视器):

0.62/-0.52
0.63/-0.52
0.63/-0.52
0.64/-0.53
0.66/-0.53
0.67/-0.53
0.66/-0.54

到这里为止,一切都应该正常。 没什么特别的。 当我将bufferUntil()readStringUntil()函数的参数更改为除'\\ n'以外的任何参数时, 都会发生问题。 当然,当我这样做时,我也会更改arduino代码中的相应部分。 例如,当用“ k”替换“ \\ n”时,从arduino串行监视器看到的传入数据看起来像,

45.63/22.3k21.51/77.32k12.63/88.90k

并继续这样。 但是处理无法获得每个缓冲区中的第二个值。 当我还在处理控制台上打印值来检查它时,我得到了第一个值(roll),但是第二个值(pitch)显示为NaN。 那是什么问题呢? 它仅在为'\\ n'时才起作用的原因是什么。

我现在无法检查,但我认为您可能有两个问题。

首先,您不需要同时使用bufferUntil()readStringUntil()

其次,更重要的是,两个函数都将字符作为一个int因此,如果要读取直到字符k ,则应该执行以下操作:

data = myPort.readStringUntil(int('k'));

或者,由于k是ASCII代码107:

data = myPort.readStringUntil(107);

如果您在执行错误的操作时以错误的类型调用该函数,则不会发生任何事情,并且该端口将继续读取,直到找到默认的换行符为止。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM