Timer1 goes too fast when used within a class

Hi guys,

I would like to use a timer within a class.

I started trying to include TimerOne.h to my class header and then using Timer1.

MyClass.h:

#ifndef MYCLASS_H
#define MYCLASS_H

#include "TimerOne.h"

class MyClass {
    /* ATTRIBUTES */
    private:
        static MyClass *_instance;

    /* FUNCTIONS */
    public:
        MyClass(int useless);            
        ~MyClass() {
        }
    private:
        static void myIsr(void);
};

#endif  /* MYCLASS_H */

MyClass.cpp:

#include "MyClass.h"

MyClass* MyClass::_instance;            // Instantiate the static pointer

MyClass::MyClass(int useless) { 
    _instance = this;   
    Timer1.initialize(5000000);
    Timer1.attachInterrupt(myIsr);
}

void MyClass::myIsr(void) {
    Serial.println("Should be printed every 5s...");
}

myClass.ino:

#include <MyClass.h>

MyClass myObj(0);

void setup() {
  Serial.begin(9600);
}

void loop() {
}

The code compiles without any complaint.
During execution the message is printed on the screen but with a period (visibly) less than 5 s!
Trying to change the period seems not to have any effect.
What’s wrong with that code?
Thank you in advance for your collaboration.

Regards,
Marco

Your problem is that you are initializing the timer stuff in the constructor. Then you construct your instance at global scope so the constructor gets run before init() runs. When init() runs to set up the hardware at the beginning of main() your timer stuff gets overwritten.

Instead of setting the timer up in the constructor, make yourself a begin() or init() method that you can call from setup once it is safe to set up the timer.