2012-11-26 109 views
2

目前是大學的學生,決定跳過我的編程課,並有點兒用指針玩。這應該採取一個特定的串行輸入,並改變我連接到Teensy ++ 2.0的三個LED的狀態。但是,它似乎只是讓我回到第一個輸入。
http://arduino.cc/en/Serial/ReadBytesUntil
這是我對ReadBytesUntil引用()的輸入變#,#,###(1,1,255就是一個例子)
我想基本上我的問題是,不ReadBytesUntil()處理逗號?如果是這樣,這裏發生了什麼?輸入字符串上的teensy指針

編輯 - 我問我的老師,甚至他不知道爲什麼它不起作用。

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); 
} 
+0

我很抱歉,如果這真的很愚蠢。這是我在此的頭一篇博文。 – Solidus

+1

輸出是什麼? 'whichLED','onoff'和'powerLevel'應該分別爲「1,1,255」,「1,255」,「255」,因爲dataFinder()不是終止任何字符串的NUL。編輯:你沒有使用'dataFinder()'的返回值,所以'str'在'inputDecoder()'中總是有相同的值,嘗試'str = dataFinder(str);' – SpacedMonkey

回答

1

inputDecoder()str是從全球範圍內,而不是在dataFinder()str,其具有局部範圍。

想象一下這樣的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()所以它不帶任何參數,因此不能照搬變量。

+0

太棒了。這似乎解決了它。它最後不喜歡我的三位數字代碼,但我可以用數學來解釋這一點。非常感謝! – Solidus