2

目前是一名大学学生,决定跳到我的编程课之前,用指针来找点乐子。这应该采用特定的串行输入并更改我连接到 Teensy++2.0 的三个 LED 的状态。然而,它似乎只是给了我第一个输入。
http://arduino.cc/en/Serial/ReadBytesUntil
这是我对 ReadBytesUntil() 的参考 输入是 #,#,### (1,1,255 是一个例子)
我想基本上我的问题是,ReadBytesUntil( ) 处理逗号?如果是这样,这里发生了什么?

编辑——我问过我的老师,甚至他也不知道为什么它不起作用。

char *dataFinder(char *str){
  while (*str != ','){
    str++;
  }
  str++;
  return str;
}

void inputDecoder(){
  str = incomingText;
  whichLED = *str;
  dataFinder(str);
  onoff = *str;
  dataFinder(str);
  powerLevel = *str;
}



void loop(){
  int length;
  if (Serial.available() > 0 ){      //this is basically: if something is typed in, do       something.
length = Serial.readBytesUntil(13,incomingText, 10);  //reads what is typed in, and stores it in incomingVar
incomingText[length]=0;  ///swapping out cr with null 
inputDecoder();
//ledControl();
Serial.print("Entered:");
//incomingText[9]=0;
Serial.println(incomingText);  //Here for testing, to show what values I'm getting back.
Serial.println(whichLED);
Serial.println(onoff);
Serial.println(powerLevel);
}
  delay(1000);
}
4

1 回答 1

1

strininputDecoder()来自全局范围,与具有本地范围的strin不同。dataFinder()

想象一下这张 ASCII 图片是内存的布局:

  str
+-----+-----+-----+-----+     +-----+-----+-----+-----+-----+-----+-----+-----+
|  *  |     |     |     | ... |  1  |  ,  |  1  |  ,  |  2  |  5  |  5  | \n  |
+--|--+-----+-----+-----+     +-----+-----+-----+-----+-----+-----+-----+-----+
   | 
   |
   \-----------------------------^

当你传递strdataFinder()它时,它会创建一个指针的副本,我称之为str'

  str         str'
+-----+-----+-----+-----+     +-----+-----+-----+-----+-----+-----+-----+-----+
|  *  |     |  *  |     | ... |  1  |  ,  |  1  |  ,  |  2  |  5  |  5  | \n  |
+--|--+-----+--|--+-----+     +-----+-----+-----+-----+-----+-----+-----+-----+
   |           \-----------------^
   |
   \-----------------------------^

dataFinder()增量str时,它确实在改变str'

  str         str'
+-----+-----+-----+-----+     +-----+-----+-----+-----+-----+-----+-----+-----+
|  *  |     |  *  |     | ... |  1  |  ,  |  1  |  ,  |  2  |  5  |  5  | \n  |
+--|--+-----+--|--+-----+     +-----+-----+-----+-----+-----+-----+-----+-----+
   |           \-----------------------------^
   |
   \-----------------------------^

然后,当您返回时,inputDecoder()取消引用str仍指向字符串的开头。

您可以使用以下方法将值分配str'回全局str

str = dataFinder(str);

或更改dataFinder(),使其不带参数,因此不复制变量。

于 2012-11-26T15:08:28.527 回答