Forcing users of your library to implement functions for their hardware.

Hi...

I am not sure how to ask this but I will try my best to explain what I want to do.

I want to execute a function inside my custom library that needs to be declared inside
the ino Arduino IDE file.

What this achieves is that I can execute user defined code inside my library at
required intervals. Basically I have an event and I want to give the user the capability
to define what they want to do when my event fires.

Being able to do the above enables the user to write code suited for their hardware to
work with my library.

I am sure this is doable I just can't get working with the Arduino IDE.

In C# this can be done with interfaces and events. But I can’t seem to find a example of this for Arduino.

I have looked at Function pointers but my libraries code can’t see the code in the Arduino IDE.

Normally you would do what attachInterrupt does.

In your library you keep a "function pointer". The user calls an assignment function passing the address of their callback function. That address is then assigned to the pointer. You then call the pointer as a function and it calls the user's function.

Something like (untested):

void (*callbackFunction)();

void __myClass::attachCallback(void (*func)())
{
  callbackFunction = func;
}

void __myClass::doSomething()
{
  if (callbackFunction) {
    callbackFunction();
  }
}

And at the user's end:

__myClass classInstance;

classInstance.attachCallback(&myCallbackFunction);
//..
void myCallbackFunction()
{
  // do something here
}

The function pointer format has to match that of the function you are passing, or it b0rks.

Protoneer:
Hi...

I am not sure how to ask this but I will try my best to explain what I want to do.

I want to execute a function inside my custom library that needs to be declared inside
the ino Arduino IDE file.
...

Create a function pointer and allow the user to assign their function to it.
In your library you can then test if it is not null and call / execute it if True.

See atachInterrupt for an example of what I mean.

What majenko said too.

Thanks for the suggestions....

Will this work with C or is this just a C++ thing?

Both. Pointers (function and variable) are at the core of the C language.

For more info on attachInterrupt, you can check out the declaration in \arduino-1.0.4\hardware\arduino\cores\arduino\Arduino.h :

void attachInterrupt(uint8_t, void (*)(void), int mode);

and the actual function in

\arduino-1.0.4\hardware\arduino\cores\arduino\WInterrupts.c

thanks Majenko and Aarondc... I managed to get it work with my library. :smiley:

majenko:
Both. Pointers (function and variable) are at the core of the C language.

Pointers are also of the devil.

:blush:

Protoneer:
thanks Majenko and Aarondc... I managed to get it work with my library. :smiley:

Awesome!