LoginSignup
0

More than 5 years have passed since last update.

Arduinoで純粋仮想関数と抽象クラス

Posted at

概要

Arduinoで、OPPの純粋仮想関数と抽象クラスをお試しで使ってみた。


動作

コメントを外すと1秒置きにトグルで点灯


わかったこと

ポートの初期化用の仮想関数用意して、led.ino側ハードに依存するポートの初期化をしようかな。


led.ino
//純粋仮想関数と抽象クラス

#include "Arduino.h"
#include "app.h"

class MyApp : public App{ // Appを継承して派生クラスMyApp
  public:
  MyApp(int ms):App(ms){}
//  void tick();          // コメントにするとapp.cppのtick()が使われる
  void tack();            // led.inoで以下で定義したtack()が使われる
};

#if 0
void MyApp::tick(){ // Appクラスのtick()はユーザーカスタマイズ項目
  digitalWrite(4, HIGH);  
  digitalWrite(5, LOW);  
}
#endif

void MyApp::tack(){ // Appクラスのtack()はユーザーカスタマイズ項目
  digitalWrite(4, LOW);  
  digitalWrite(5, HIGH);  
}

//------------------------------------------------------------------
// Arduino固有の関数 setup() :初期設定
//------------------------------------------------------------------
void setup() {
  pinMode(4, OUTPUT);  // ピンモードを指定
  pinMode(5, OUTPUT);  // ピンモードを指定

  Serial.begin(115200);
  Serial.println("");
  Serial.println("純粋仮想関数と抽象クラス");
}

//---------------------------------------------------------------------
// Arduino main loop
//---------------------------------------------------------------------
void loop() {
  MyApp the_app(1000);// 1000msタイマー
  the_app.run();
}
app.h
#ifndef __app_h
#define __app_h
// ↑クラス、変数、インライン関数などの二重定義エラーの防止、コンパイル時間の短縮

// クラスの定義
class App {
  int interval_;
  public:
    App(int sec) : interval_(sec) {}
    void run();
    virtual void tick();  // 純粋仮想関数
    virtual void tack();  // 純粋仮想関数
};
#endif // __app_h
app.cpp
#include "app.h"
#include "Arduino.h"

//extern "C" void delay(unsigned int sec);

void App::run(){
  static int toggle = 1;
  for(;;){
    delay(interval_);
    if (toggle)
      tick();
    else
      tack();
    toggle = 1 - toggle;
  }
}

void App::tick(){}
void App::tack(){}

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0