I would like to implement a callback mechanism (to my class) similar to serial.attach()
where you assign your own function when na IRQ is generated. Is it possible that the class will send me a not only IRQ but some result too? ie:
test.h
#include "mbed.h"
class Test {
public:
Test();
void something();
int get();
void attach(Callback<void()> function);
private:
Callback<void()> _mycb;
int _number;
};
test.cpp
#include "mbed.h"
#include "test.h"
static void donothing() {}
Test::Test() {
_mycb = donothing;
_number = 0;
}
void Test::something() {
//...
_number = 123; // how to pass this to my callback
_mycb.call();
}
int Test::get(){
return _number;
}
void Test::attach(Callback<void()> function) {
if (function) {
_mycb = function;
} else {
_mycb = donothing;
}
}
main.cpp
#include <mbed.h>
#include "test.h"
Test test;
void callback() {
printf("get number here somehow\n");
// or is this the only way
printf("number: %i\n", test.get());
}
int main() {
test.attach(callback);
test.something();
while (true);
}
You can change the declaration of your callback to accept parameters ? Callback class supports that. Need to change Callback<void()> _mycb;
Or as you did via a global accessible object (as I read the code, you are getting the number as the object is visible, and get method would return number member).
Please have a look at our introduction to callback objects.
Didn't see that, thank you
Most helpful comment
Please have a look at our introduction to callback objects.