class 内的中断

Interrupts within a class

我正在尝试编写一个库来使用中断计算 PWM 占空比。我知道 class 成员不是 attachInterrupt 的正确函数格式。

但是,我已经尝试按照这个 post Calling an ISR from a class by Nick Gammon 进行操作,但令人沮丧的是我仍然收到错误消息:

cannot declare member function 'static void PWMin::risingInt()' to have static linkage

有人可以阐明我的代码有什么问题或任何其他建议吗?

这是 cpp 文件:

#include "PWMin.h"

PWMin::PWMin(int intPin, int* outputTime, bool direction=true){
    instance = this;

    this->_intPin = intPin;
    this->_outputTime = outputTime;
    this->_direction = direction;

    pinMode(this->_intPin, INPUT);
    attachInt();
}

void PWMin::attachInt(){
    attachInterrupt(this->_intPin, this->_direction ? risingInt : fallingInt, this->_direction ? RISING : FALLING);
}

void PWMin::risingISR(){
    this->start = micros();
    this->_direction = false;
    this->attachInt();
}

void PWMin::fallingISR(){
    this->timeElapsed = micros() - this->start;
    *_outputTime = this->timeElapsed;
    this->_direction = true;
    this->attachInt();
}

unsigned long PWMin::lastElapsedTime(){
    return this->timeElapsed;
}

static void PWMin::risingInt(){
    if(PWMin::instance != NULL){
        PWMin::instance->risingISR();
    }
}

static void PWMin::fallingInt(){
    if(PWMin::instance != NULL){
        PWMin::instance->fallingISR();
    }
}

这是头文件:

#ifndef PWMin_h
#define PWMin_h

class PWMin {
    public:
        PWMin(int intPin, int* outputTime, bool direction);
        unsigned long lastElapsedTime();

    private:
        static PWMin *instance;

        int _intPin;
        int* _outputTime;
        bool _direction;
        unsigned long start, timeElapsed;

        void attachInt();
        void risingISR();
        void fallingISR();
        static void risingInt();
        static void fallingInt();
};

#endif /* PWMin_h */

谢谢, 肖恩

在头文件中,您已将函数声明为 static,因此无需在 .cpp 文件中再次声明。

类似问题有一个很好的答案 here 进一步说明原因。