Shaun Barney
Shaun Barney

Reputation: 748

Interrupts within a class

I am trying to write a library to calculate the PWM duty period using interrupts. I understand a class member is not the right format of function for attachInterrupt.

However, I have tried to follow this post Calling an ISR from a class by Nick Gammon, who has a work around, but frustratingly I'm still getting the error:

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

Can someone please shine some light on what's wrong with my code or any other suggestions?

This is the cpp file:

#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();
    }
}

This is the header file:

#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 */

Thanks, Shaun

Upvotes: 3

Views: 2929

Answers (1)

Scott Stainton
Scott Stainton

Reputation: 394

In your header file you have declared your functions as static, therefore there is no need to do so again in your .cpp file.

There is a good answer to a similar question here for further clarification on why.

Upvotes: 3

Related Questions