首先,设置:Arduino IDE 1.5.7 beta,Nano v3.0
简而言之,我的目标是:在继续执行以下代码之前,使用 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
};
}
好的,bar1
和 bar2
中的内容有两个不同的问题
如果 bars
分别是 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
但随后也提示 char 输入应该是一个指针 (char*):
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 值。无论如何,如果 bar1
和 bar2
被引用为 &charCr
和 &charNl
代码编译正常,但条件永远不会遇到了,我知道我发送了两个 EOL 字符,通过不同的方式和调试代码确认。
那么...我的代码出了什么问题?
最佳答案
网站上的文档具有误导性,因为他们说的是 string 但函数原型(prototype)是 (char)。 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))
关于c++ - Arduino:Serial.find(char) 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25964731/