Mbed-os: Callback: pass result?

Created on 11 Jan 2018  路  3Comments  路  Source: ARMmbed/mbed-os

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);
}

Description

  • Type: Question

Most helpful comment

Please have a look at our introduction to callback objects.

All 3 comments

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

Was this page helpful?
0 / 5 - 0 ratings