Arm Mbed and Pelion Device Management support forum

Pass a function with arguments and timeout

How I can I pass a function with arguments in Time out (like the code below):

Timeout flipper;

void flip(int x) {
      pc.printf("%d", x)
 }

int main() {

    flipper.attach(&flip(2),  2); //  I want to pass an argument here but compiler gives an error
    while(1) {}

}

Hello Hassan,

Timeout's attach function expects a Callback<void()> function so I’m afraid you cannot pass it argument(s) directly. However, you can use global variables (shared memory) for that.

For example:

Timeout      flipper;
volatile int sharedVar;

void flip()
{
    printf("%d", sharedVar);
}

int main()
{
    sharedVar = 2;
    flipper.attach(flip,  2);
    while(1) {}
}

The volatile qualifier prevents the compiler from removing the related code during optimization. For more info read this.

Best regards,

Zoltan

Thanks