Call function in main program from library in Arduino

I just started building libraries in Arduino. I created a library called inSerialCmd. I want to call a function called delegate () that is defined in the main program file, stackedcontrol.ino, after including the inSerialCmd library.

When I try to compile, one error is thrown:

... \ Arduino \ libraries \ inSerialCmd \ inSerialCmd.cpp: in member function 'void inSerialCmd :: serialListen ()': ... \ Arduino \ libraries \ inSerialCmd \ inSerialCmd.cpp: 32: error: "delegate" not was announced

After a bit of searching, it seemed like adding a scope resolution operator might do the trick. So I added "::" before delegate (), now ":: delegate ()", but the same error is thrown.

Now I'm stumped.

+3


source to share


1 answer


You cannot and should not directly call a function in a program from a library. Keep in mind the key aspect that turns a library into a library:

The library is application-independent. The library can be fully compiled and packaged into an .a file without the program existing.

So there is a dependency on one path, the program depends on the library. This, at first glance, may prevent you from achieving what you want. You can get the functionality you are asking about through what is sometimes called a callback. The main program provided the library at runtime with a pointer to the function to execute.

// in program somwehere
int myDelegate(int a, int b);

// you set this to the library
setDelegate( myDelegate );

      



You can see this in arduino if you look at how interrupt handlers are set. This same concept exists in many environments - event listeners, action adapters - all with the same purpose - to enable a program to define a specific action that the library cannot know.

The library will store and call the function using the function pointer. Here's a rough sketch of what it looks like:

// in the main program
int someAction(int t1, int t2) {
  return 1;
}

/* in library
this is the delegate function pointer
a function that takes two int and returns an int */
int (*fpAction)(int, int) = 0;   

/* in library
this is how an application registers its action */
void setDelegate( int (*fp)(int,int) ) {
  fpAction = fp; 
}

/* in libary
this is how the library can safely execute the action */
int doAction(int t1, int t2) {
  int r;
  if( 0 != fpAction ) {
    r = (*fpAction)(t1,t2);
  }
  else {
    // some error or default action here
    r = 0;
  }
  return r;
}

/* in program
The main program installs its delegate, likely in setup() */
void setup () {
  ...      
  setDelegate(someAction);
  ...

      

+5


source







All Articles