Saturday, September 17, 2011

C/C++ Callback functions

So one of my projects I have been working on with the Arduino UNO required the use of an interrupt. For those not familiar with an interrupt it essentially is a mechanism that allows the code to branch off of its normal routine and execute a separate set of code. This is great for devices such as a rotary encoder that act as a volume knob or some other control mechanism since it will immediately interrupt the current code and execute the code associated with the interrupt. I was developing a nice set of library functions for a rotary encoder class library and thought that it would be nice to have a command like:

Rotary ROT;
ROT.begin(EncA,EncB,PB,CallbackFcn);

The purpose of this method would be to configure the rotary encoder inputs (EncA, EncB) to their proper modes and then create a callbackfcn that would execute every time one of these changed. The arduino library has a function that allows you to attach an interrupt to a pin and associate that interrupt pin with a callback function. But I wanted to allow the user to utilize my Rotary Class without having to specify the callback function within the library itself. This required me to learn how to create a "function pointer".

To create a function pointer is simple. Suppose we have a local function called CallbackFcn that takes in no input arguments. We can create a method that takes a function pointer as an input argument such as:

void Rotary::begin(int EncA, int EncB, int PB, void (*CALLBACK)(void)){
 //Stuff goes here
}

That is all there is to it.