How to set the value to zero for example after two second in Ticker

Hello everybody,

I wannt to set a value for two seconds and after two seconds I wannt to set the value to Zero the next two seconds and continue… . I tryied to used Ticker for this Purpose but it does not work. Could you have any Suggestion or idea?

#include "mbed.h"
 

Ticker t1,t2;
 float ManVal1;
 
void flip() {
    ManVal1 = 25;
    printf("x= %f\n",ManVal1); 
} 
  
void eventFunction() {
      
        ManVal1 = 0;
        printf("x= %f\n",ManVal1); 
        
}
 
int main() {
    
    printf("starting.....\n"); 
    
    ManVal1 = 0;
    t1.attach(&flip, 2.0);   
    t2.attach(&eventFunction, 4.0); 
         
    while(1) {
           
    }
    
}

Thank you very much!
Nahom

I would just use one Ticker and flip the value in the callback like this.

void flip() {
    static bool flag = false;
    ManVal1 = flag ? 0 : 25;   // 0 or 25 depending on the flag
    flag = !flag;              // flip flag
    queue->call(&userContext); // defer the execution to a different context
} 

I flip flag which is bool. And set a value depending on the state of flag.

Now, you don’t want to printf in an ISR context. I would use EventQueue to defer the execution to another context.
https://os.mbed.com/docs/mbed-os/v5.15/tutorials/the-eventqueue-api.html

EventQueue *queue = mbed_event_queue(); // event queue

void userContext() {
    printf("x= %f\n",ManVal1);
}

If you just want to print the value every 2 seconds, this declaration is ok.

float ManVal1;

But, if you want to access it in main, you want to add volatile keyword because this value can be modified by an ISR function.

volatile float ManVal1;

Try this code below. It flips ManVal1 and a LED every 2 secs. If you remove volatile keyword, LED doesn’t blink.

#include "mbed.h" 
Ticker t1;
volatile float ManVal1;
DigitalOut led(LED1);
EventQueue *queue = mbed_event_queue(); // event queue

void userContext() {
    printf("x= %f\n",ManVal1);
}

void flip() {
    static bool flag = false;
    ManVal1 = flag ? 0 : 25;   // 0 or 25 depending on the flag
    flag = !flag;              // flip flag
    queue->call(&userContext); // defer the execution to a different context
} 
 
int main() {
    
    printf("starting.....\n"); 
    
    ManVal1 = 0;
    t1.attach(&flip, 2.0);   
         
    while(1) {
        led = ManVal1 == 25 ? 1 : 0;
    }
}

It works! Thanks Kentaro.

regards,
Nahom