c++ - Arduino:Serial.find(char) 不工作

标签 c++ stream serial-port arduino

首先,设置: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
      }; 
}

好的,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

找到一个接近的匹配项,我相信这是查找的正确定义,因为 SerialStream

继承了它
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 值。无论如何,如果 bar1bar2 被引用为 &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/

上一篇:c++ - 空/全链表

下一篇:c++ - 计算利率

相关文章:

c++ - 带 <T> 或不带 (C++) 的类模板

c++ - 如果我在 C++ 中将(指向类 A 的指针)转换为(指向其子类 B 的指针)会发生什么

c++ - 如何参数化构造函数的参数个数?

c - 在不同函数的回调中使用函数

c++ - 我的 Dll 大小因引入大型 switch case 而过大,如何减小 Dll 大小(MSVC C++)?

c++ - 在其他类中声明的私有(private)成员

node.js - 管道到 spawn stdin

c - 为什么我无法在 Raspberry Pi 上使用 D2XX 访问我的 FTDI 设备?

c - select() 似乎不适用于 TTY

scala - Scala 中的非严格、不可变、非记忆化的无限系列