割り込み / 通常のメンバー函数としてISRをクラス内に記述する

pp.37-39

前回はISRをグローバル函数として記述したが、それと同じことを今度はクラスのメンバー函数として記述してみる。

テキストによれば、通常のメンバー函数として記述する方法と、staticなメンバー函数として記述する方法とがあるとの由。まずは通常のメンバー函数として記述してみる。

#include "mbed.h"

class MyTimeout{
    typedef Kernel::Clock::duration_u32 chrono_t;

    private:
    uint8_t on;

    // Mbed Timeoutクラスをインスタンス化する。
    Timeout timer;

    // これがISR。
    void at_timeout(){
        on = 0;
    }

    public:
    void start(chrono_t time){
        on = 1;

        // Mbed TimeoutクラスのインスタンスにISRをattachする。
        // attachするときはcallback(this, &クラス名::函数名)という構文を使う。
        timer.attach(callback(this, &MyTimeout::at_timeout), time);
    }
    uint8_t IsOn(){
        return on;
    }

    // コンストラクタ
    MyTimeout(){}
};

int main(){
    DigitalOut led(PA_10);

    MyTimeout timer;
    timer.start(5s);

    while(timer.IsOn()){
        led = !led;
        ThisThread::sleep_for(250ms);
    }

    return 0;
}