2014-09-21 90 views
0

首先,設置:Arduino的IDE 1.5.7測試版,納米V3.0的Arduino:Serial.find(炭)不工作

總之,我的目標是:用Serial.find()等爲標準EOL在繼續下面的代碼之前,在串行緩衝區中找到字符(ASCII 13,CR和ASCII 10,NL)。

我的(問題/縮短)代碼:

char charCr = 13; 
char charNl = 10; 

void loop(){ 
    do_stuff; 
    foo(); 
    do_other_stuff;} 

void foo() 
{ 
     while (true) 
     { 
      if (Serial.find(bar1) && Serial.find(bar2)) 
      { 
       break; // EOL characters found 
      } 
      delay(1); // wait to receive EOL 
     }; 
} 

好,所以兩次與在發生什麼bar1bar2

如果bars分別爲charCrcharNl然後代碼不開的問題編譯時抱怨:

error: call of overloaded 'find(char&)' is ambiguous 
note: candidates are: 
In file included from C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/HardwareSerial.h:29:0, 
from C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/Arduino.h:221 

找到一個近似匹配,其中,我從Stream

C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/Stream.h:59:8: note: bool Stream::find(char*) <near match> 
bool find(char *target); // reads data from the stream until the target string is found 

相信的是找到正確的定義,爲Serial inhereits它但隨後也抱怨焦炭輸入應該是一個指針(字符*):

C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/Stream.h:59:8: note: no known conversion for argument 1 from 'char' to 'char*' 

文檔我讀過在Serial.find()和Stream.find()表明char應該是而不是是一個指針,只是爲了傳遞char值。無論如何,如果bar1bar2被引用爲&charCr&charNl代碼編譯得很好,但條件從未滿足,並且我知道我發送了兩個EOL字符,如通過不同方法和調試代碼所證實的。

那麼......我的代碼出了什麼問題?

+0

從評論:即「直到目標串中發現從流中讀取數據」。不是字符串,這就是爲什麼它要求指針。 – 2014-09-21 23:30:40

+0

是的,但它也說輸入數據類型「目標:搜索字符串(char)」...所以什麼纔是正確的語法?爲什麼當我使用參考操作符&它沒有找到它? – brneuro 2014-09-21 23:32:57

+0

嘗試一下 - 搜索以空字符結尾的CR/LF字符串,看看是否有效。如果有疑問,懷疑文檔,(特別是如果我寫了:)。 – 2014-09-21 23:34:30

回答

1

該網站上的文檔是誤導性的,因爲他們說字符串但函數原型是(char)。 A 字符串是一個可變長度字符數組。 A char是單個字符。如果有疑問,請始終相信頭文件(.H)中的函數聲明。從Stream.h開始:

bool find(char *target); // reads data from the stream until the target string is found 
// returns true if target string is found, false if timed out (see setTimeout) 

bool find(char *target, size_t length); // reads data from the stream until the target string of given length is found 
// returns true if target string is found, false if timed out 

考慮到這些,有兩種方法。搜索單個字符:

// method as you started - accepts terminators in either order 
char charCr = 13; 
char charNl = 10; 

if (Serial.find(&charCr, 1) && Serial.find(&charNl, 1)) 

或字符串形式:

char termseq1[] = {13, 10, 0}; 
char termseq2[] = {10, 13, 0}; 

if (Serial.find(termseq1) || Serial.find(termseq2)) 
+0

這是真的,也在我的OP與Martin James的評論中提到。但是,在其他方面令人失望,因爲我相信Serial.find()以破壞緩衝的方式工作,如Serial.read(),而不是Serial.peek()...我希望等待EOL後面跟一個整數即將被接收,然後使用Serial.parseInt()來獲取它。似乎我將不得不找出另一個解決方案。謝謝 – brneuro 2014-09-21 23:54:26