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


9

我正在用Arduino 0022编写程序。

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

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

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

Answers:


3

您不应从头文件中调用函数。头文件用于定义预处理程序宏(#define),并引用其他文件中的变量/函数。

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

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

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

然后,您需要添加一个或多个“ 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 ++新手,您的回答对我很有帮助,我一定会采纳您的建议。即使这样,我还是对为什么在主草图之外无法使用Serial类感兴趣。干杯!
2011年

3

作为@Majenko的一个很好的答案的替代方法,您可以制作一个C ++类来封装您的函数,然后按照http://www.arduino.cc/zh/Hacking/LibraryTutorial中的描述将其放入库文件夹中。

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


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

嗨!是的,我在arduino库目录中浏览了Serial.h或类似文件,而我所能找到的只是HardwareSerial.h,其中没有我需要的定义。最后,我偶然发现了包含<WProgram.h>的解决方案,该方案似乎声明了Serial对象。
2011年

0

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

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

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


1
好的,如果您想确保与Arduino 1.0兼容,则应根据ARDUINO编译标志有条件地包含该名称或“ Arduino.h”,有关详细信息,请参见我的答案。另外,我的答案中的教程链接说,您的课程中始终包含WProgram.h
vicatcu 2011年
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.