Implementing ISR in C++ for AVR Mega

206 Views Asked by At

I have succeeded in creating a Timer Class with an interrupt handler in C++ but struggling to understand why my ISR can only update if the variable is globally scoped and will not update a fully encapsulated member variable. I would like to achieve as shown below where the ISR handler updates the member variable. I'm missing something so would appreciate some help/feedback.

This is what I tried. It compiles but will not update the member variable.

extern "C" void TIMER0_COMPA_vect(void) __attribute__((interrupt));
#define F_CPU 20000000UL

class Timer0 {
    volatile uint16_t counter;
    public:
        static Timer0* pTimer0;
        void handle_interruptTIMER0(void);
        void TIMER0_init(void);
        unsigned int getCounter(void);
        Timer0(const unsigned long);
        ~Timer0();   
};

// Define
Timer0* Timer0::pTimer0;

ISR(TIMER0_COMPA_vect)  {
    Timer0::pTimer0->handle_interruptTIMER0();
}

void Timer0::handle_interruptTIMER0(void)
{   
    PORTD ^= (1 << 7);  // Debug bit PORTD Pin 7 OP_CLK_PIN
    pTimer0->counter++;
}

I would like to be able to update a fully encapsulated variable in the ISR Handler

1

There are 1 best solutions below

1
David Grayson On

Like @AviBerger hinted at, you likely are forgetting to initialize pTimer0 to point to a Timer0 object. Since the AVR only has one Timer0, it doesn't make too much sense to use a pointer. You can get rid of the pointer and just declare a global instance with a static storage duration by writing this after the class definition:

Timer0 timer0;