C++ Arduino:序列。查找(字符)不工作
首先,设置:Arduino IDE 1.5.7测试版,Nano v3.0 简而言之,我的目标是:在继续执行以下代码之前,使用Serial.find()等待在串行缓冲区中找到两个标准下线字符(ASCII 13、CR和ASCII 10、NL) 我的(有问题/缩短的)代码: 好的,C++ Arduino:序列。查找(字符)不工作,c++,stream,serial-port,arduino,C++,Stream,Serial Port,Arduino,首先,设置:Arduino IDE 1.5.7测试版,Nano v3.0 简而言之,我的目标是:在继续执行以下代码之前,使用Serial.find()等待在串行缓冲区中找到两个标准下线字符(ASCII 13、CR和ASCII 10、NL) 我的(有问题/缩短的)代码: 好的,bar1和bar2 如果条分别为charCr和charNl,则代码在抱怨时不会编译: error: call of overloaded 'find(char&)' is ambiguous note: candid
bar1
和bar2
如果条
分别为charCr
和charNl
,则代码在抱怨时不会编译:
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
查找一个近似匹配项,我认为这是查找的正确定义,因为Serial
从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.find()和Stream.find()的文档表明,char不应该是指针,而应该传递char值。无论如何,如果bar1
和bar2
被引用为&charCr
和&charNl
,则代码编译良好,但从未满足条件,并且我知道我正在发送两个EOL字符,通过不同的方式和调试代码确认
所以。。。我的代码出了什么问题?网站上的文档有误导性,因为他们说string,但函数原型是(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))
从注释:'从流中读取数据,直到找到目标字符串',即。不是char,STRING,这就是它请求指针的原因。是的,但它也表示输入数据类型“target:the STRING to search for(char)”。。。那么正确的语法是什么呢?为什么,当我使用reference操作符时&它没有找到它吗?尝试一下-搜索以null结尾的CR/LF字符串,看看是否有效。如果有疑问,怀疑文档,(尤其是我写的):好,试试看,但是请原谅我天真,我不是C++专家,什么是定义一个空结尾的CR/LF字符串的语法?似乎“Char CRLFNL(3)={ 13, 10, 0 };”可能工作,仍然在计算这是真的,在我的OP评论中也提到了Martin James。然而,在其他方面令人失望,因为我相信Serial.find()以破坏缓冲区的方式工作,例如Serial.read(),而不是Serial.peek()。。。我希望在接收到一个整数后等待EOL,然后使用Serial.parseInt()获得它。看来我得想出另一个解决办法了。谢谢
// 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))