Arduino单个功能的调试往往会把代码都写在ino文件的setup和loop方法中,现实中一款完整的产品会有很多功能组成,需要遵循一定的结构设计规则做到复用性、模块化、解耦等,将功能按一定规则分割成多个文件,在Arduino ide中我们可以创建多个h文件和c/cpp文件来合理的设计分割功能模块。
创建头文件
#ifndef Motion_h
#define Motion_h
class Motion
{
public:
void setup (); // 初始化引脚
void advance (int a); // 前进
//void right (int b) //右转单轮
};
#endif
添加cpp文件
和创建头文件一样New Tab添加CPP文件
#include "motion.h"
#include <Arduino.h>
void Motion::setup()
{
}
void Motion::advance (int a)
{
Serial.println("advance");
}
ino主文件调用
#include "motion.h"
Motion motion;
void setup() {
// put your setup code here, to run once:
motion.setup();
}
void loop() {
motion.advance(1);
}
接下来你可以合理规划你的功能模块代码到不同的类文件里了