以Led为例,
LED有点亮,熄灭,翻转三种状态
还需要有设置引脚号,读取引脚电平的接口
在LED.h中定义一个Led类
#ifndef LED_H
#define LED_H
#include "Arduino.h"
//定义一个Led类
class Led {
private: //私有的
byte _pin;
public: //公共的
Led(byte _pin_param) ;//构造函数
~Led() ;//析构函数,用于释放内存
void setpin(byte pin_param);
byte getpin() const ;
void on() const ;
void off() const ;
void toggle() const ;
};
#endif
把引脚号设置为Led类私有,外部只能通过setpin函数访问
在Led.cpp中定义Led方法用"Led::"表示是Led类中的方法
定义构造函数Led调用setpin函数,简化Led引脚定义
定义析构函数~Led,用与跳出函数前释放资源
#include "Led.h"
//构造函数,用于设置pin
Led::Led(byte pin_param)
{
setpin(pin_param);
}
Led::~Led()
{
Serial.println("释放内存");
}
void Led::setpin(byte pin_param){
if(pin_param<40&&pin_param>0){
_pin=pin_param;
pinMode(_pin, OUTPUT);
}
else{
Serial.println("pin_eeror");
}
}
byte Led::getpin ()const
{
return _pin;
}
void Led::on ()const
{
digitalWrite(_pin, LOW);
}
void Led::off ()const
{
digitalWrite(_pin, HIGH);
}
void Led::toggle ()const
{
digitalWrite(_pin, !digitalRead(_pin));
}
在led.ino中定义三个LED对象并绑定对应引脚
在初始化函数中打印一个LED对象所占的字节数,可以看到它只占一个字节
在循环中调用led对应的方法就可以控只led灯亮灭了!
#include "Led.h"
Led ledred(12),
ledyellow(13),
ledblue(14); //定义3个Led对象
//初始化
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
Serial.println("start");
// ledred.pin=12; //直接访问
//ledred.setpin(12); //间接访问
Serial.print(sizeof(ledred));
Serial.println(" byte");
}
void loop() {
// put your main code here, to run repeatedly:
delay(500); // this speeds up the simulation
ledred.toggle();
//digitalWrite(12, !digitalRead(12));
//ledred.toggle();
}