课程简介
– 子类继承
– public继承类型
本节教程结束后程序代码状态 (无法复制本站代码?请点击这里找到原因。)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
/* * 零基础入门学用Arduino教程 * 第四章 - 专项教程 * 第二部分 - 面向对象编程 示例程序 - 5 * 太极创客 WWW.TAICHI-MAKER.COM * 2019-04-21 */ #include "Led.h" PwmLed myPwmLed; void setup() { Serial.begin(9600); myPwmLed.setLedPin(3); int myPwmLedPin = myPwmLed.getLedPin(); Serial.print("int myPwmLedPin = "); Serial.println(myPwmLedPin); } void loop() { for(int i = 0; i < 255; i++){ myPwmLed.on(i); Serial.print("myPwmLed.getPwmVal() = "); Serial.println(myPwmLed.getPwmVal()); delay(10); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
#ifndef _LED_H_ #define _LED_H_ #include <Arduino.h> class Led { public: Led(); Led(int userLedPin); ~Led(); void on(); void off(); int getLedPin(); void setLedPin(int userLedPin); private: int ledPin = 2 ; }; class PwmLed : public Led{ public: void on(int userPwmVal); int getPwmVal(); private: int pwmVal = 0; }; #endif |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
#include "Led.h" Led::Led(){ Serial.println("Led Object Created."); pinMode(2, OUTPUT); } Led::Led(int userLedPin) { Serial.println("Led Object Created."); ledPin = userLedPin; pinMode(ledPin, OUTPUT); } Led::~Led(){ Serial.println("Led Object Deleted."); } void Led::on(){ digitalWrite(ledPin, HIGH); } void Led::off(){ digitalWrite(ledPin, LOW); } int Led::getLedPin(){ return ledPin; } void Led::setLedPin(int userLedPin){ ledPin = userLedPin; pinMode(ledPin, OUTPUT); } void PwmLed::on(int userPwmVal){ pwmVal = userPwmVal; analogWrite(getLedPin(), pwmVal); } int PwmLed::getPwmVal(){ return pwmVal; } |