LoginSignup
18
16

More than 5 years have passed since last update.

ArduinoでOOP

Last updated at Posted at 2016-10-20

正直、ArduinoでがっつりOOPで実装する機会とかあんまりないかもしれませんが、一応。。

まず、ファイル構成はこんな感じになります。

sketch_oopTest.png

文字通りLEDをコントロールする部分をクラス化してみました。

コードは以下のとおり。

Arduinoでスケッチを新規作成すると、*.inoという拡張子のファイルが作られます。
.inoにはおなじみのsetup()loop()がいます。

Arduinoのプログラムはここからスタートしますね。

sketch_oopTest.ino

sketch_oopTest.ino

void setup() {
}

void loop() {
}

次に、クラス定義をC++で書いてみます。

LedController.h

LedController.h

#ifndef LedController_h
#define LedController_h

class LedController {

  public:
    LedController(int pin);
    void on();
    void off();

  private:
    int m_ledPin;

};

#endif

LedController.cpp

(※)Arduino.hをインクルードし忘れないように注意してください!

LedController.h
#include "Arduino.h"
#include "LedController.h"

LedController::LedController(int pin) {
  m_ledPin = pin;
  pinMode(m_ledPin, OUTPUT);
}

void LedController::on(void) {
  digitalWrite(m_ledPin, HIGH);
}

void LedController::off(void) {
  digitalWrite(m_ledPin, LOW);
}

クラス定義ができたので、先ほどの.inoから、クラスを使用してみます。

sketch_oopTest.ino

#include "LedController.h"

LedController ledCont = LedController(10);

void setup() {

}

void loop() {
  ledCont.on();
  delay(100);
  ledCont.off();
  delay(100);
}

おわり。

[追記]
ちなみに、ArduinoIDEで、プロジェクト内に新規ファイルを作成する方法はちょっと変わってまして、最初とまどいました。。

以下参考

Arduino - ソースコードを複数ファイルに分割して記述する

18
16
0

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
18
16