Answers:
您不应从头文件中调用函数。头文件用于定义预处理程序宏(#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 ++类来封装您的函数,然后按照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
我找到了一种Serial
在头文件/标签中声明类/对象的方法:
#include <WProgram.h> // at the top of the file
这对我来说感觉不是很干净,但是似乎还没有任何缺点。