在单独的选项卡/头文件中调用 Serial.print

电器工程 Arduino C
2022-01-15 13:42:27

我正在用 Arduino 0022 编写程序。

在我的主草图代码中调用Serial.println工作正常,但是当我尝试Menu.h在位于单独选项卡中的头文件“”中使用它时,出现错误:

在 AppController.cpp:2 包含的文件中:
Menu.h:在构造函数“Menu::Menu()”中:
Menu.h:15:错误:“Serial”未在此范围内声明

我如何Serial.println在草图代码之外使用?

3个回答

您不应该从头文件中调用函数。头文件用于定义预处理器宏 (#define) 和对其他文件中的变量/函数的引用。

您应该在编译时创建多个 C 文件并将它们链接在一起。头文件用于告诉每个 C 文件其他 C 文件具有哪些函数和变量。

要在 Arduino IDE 中使用多个文件,您至少需要 1 个头文件来描述要在它们之间共享的其他文件中的功能。此外,您希望在所有文件中使用的任何全局变量。

这些定义应使用“外部”属性进行限定。

然后您需要添加一个或多个“pde”文件,其中包含函数的实际代码和变量定义。

例如,我有一个“mouse.h”文件:

extern void mouse_read(char *,char *, char *);
extern void mouse_init();

和一个“mouse.pde”文件:

#include <ps2.h>

PS2 mouse(6,5);

void mouse_read(char *stat,char *x, char *y)
{
  mouse.write(0xeb);  // give me data!
  mouse.read();      // ignore ack
  *stat = mouse.read();
  *x = mouse.read();
  *y = mouse.read();
}

void mouse_init()
{
  mouse.write(0xff);  // reset
  mouse.read();  // ack byte
  mouse.read();  // blank */
  mouse.read();  // blank */
  mouse.write(0xf0);  // remote mode
  mouse.read();  // ack
  delayMicroseconds(100);
}

然后在我的主文件中,我有:

#include "mouse.h"

我可以调用“mouse.pde”中的函数,就好像它们在本地文件中一样。

作为@Majenko 非常好的答案的替代方案,您可以创建一个 C++ 类来封装您的函数并将其放入库文件夹中,如http://www.arduino.cc/en/Hacking/LibraryTutorial中所述。

您可能需要#include <Serial.h>在类的实现文件中才能调用 Serial 方法。我会小心这样做,因为调用串行函数显然有副作用(特别是阅读)。我更喜欢在我的类中定义一个方法,它接受一个 char * 并将字节从串行接口从我的主程序传递到它,而不是让它直接与串行接口交互。


#if defined(ARDUINO) && ARDUINO >= 100
  #include "Arduino.h"
#else
  #include "WProgram.h"
#endif

我找到了一种Serial在头文件/选项卡中声明类/对象的方法:

#include <WProgram.h>  // at the top of the file

这对我来说感觉不是很干净,但它似乎还没有任何缺点。