Timer outside .ino file


is it possible to use a Timer outside the main .ino file, For example in a library?
I tried to declare the timer Timer timer(1000,timer_fnc); in the .cpp file with void timer_fnc(void) declared in the .h file. I get a ‘timer_fnc’ was not declared in this scope error.

Thank you

Yes, you can do that - you just need to make sure that all symbols are defined wherever you need them (once explicitly and everywhere else as extern for variables and for functions you need a function prototype/forward declaration).

Thank you.

I have declared void timer_fnc(void) in the .h and defined it in the .cpp together with the Timer initialization Timer timer(1000,timer_fnc); .

But when I compile I still get a error: 'timer_fnc' was not declared in this scope;

Could you provide an example?

If you are using Web IDE, can you provide a SHARE THIS REVISION link to see what exactly you do and what the entire error message (including file reference and related notes) tells?

Sure I could provide a working example, but in order to know the dos and don’ts it better to see why it is not working the way you did it :wink:

Here’s the link to the code. Thank you so much.

One thing that wasn’t disclosed in any of your previous post is that your timer_fnc() actually is a non-static class method.
That’s why it is important to work on your code not mine :wink:

For non-static class functions you need to use another Timer constructor

And in order to actually do that you need an object instance of your Motion_Service class.

For that reason you cannot have this in your library: Timer timer(1000, MotionService::timer_fnc); - not even with the correct constructor as you haven’t got an object at that time.

The way you laid out your library I’d rather have the Timer as a private member of the class and construct and start it in the class constructor.

Thank you. The is clear now. I rather turned the function and variable into static, I think this is a better option (?). It compiles. See updated code.

1 Like