10 years, 11 months ago.

Ticker: repeated attach and detach of functions to Ticker

All:

my application requires to intermittently send bursts of square waves out of a pin. I already need the PWM for something else, so the idea was to set up a ticker. However, it seems that something blocks if I'm trying to re-attach a function which was previously attached. The following example shows a (trivial) piece of code which executes perfectly. However, if I uncomment the one line which is commented out (the 2nd << SCKtick.attach_us(&flip, 5); >> ), it never gets to the main loop.

Does anybody know whether what I'm trying is even feasible with the Ticker library? If yes, how would one implement that?

Best Regards,

JJ

#include "mbed.h"

Ticker SCKtick;
DigitalOut SCK1(p5);

DigitalOut myled(LED1);

void flip(void) { // flip function
    SCK1 = !SCK1;
}

int main() {

    SCKtick.attach_us(&flip, 50);
    wait(0.2);    
    myled = 1;
    SCKtick.detach();    
    wait(0.5);
    myled = 0;  

    //SCKtick.attach_us(&flip, 5);

    wait(0.5);
    
    while(1) {
        myled = 1;
        wait(0.2);
        myled = 0;
        wait(0.2);
    }
}

Please use <<code>> and <</code>> around your code.

Also what happens if you attach it again with 50 instead of 5?

posted by Erik - 23 May 2013

The frequency makes no difference here. 50 is the same as 5.

posted by Jay Zee 23 May 2013

2 Answers

10 years, 11 months ago.

Hi Jay, i have an example of attaching and detaching a ticker but with an interrupt (press of a button). Maybe this will help you:

#include "mbed.h"

InterruptIn button(p5);
Ticker flipper;
DigitalOut led1(LED1);
DigitalOut led2(LED2);
int isPressed;

void flip() {
    led2 = !led2;
} 
  
void eventFunction() {
    if(!isPressed) {
        flipper.attach(&flip, 2.0);   
        isPressed=1;
    } else {
        flipper.detach();
        isPressed=0;   
    }
}

int main() {
    isPressed=0;
    led2 = 0;
    button.rise(&eventFunction);
         
    while(1) {
        led1 = !led1;
        wait(0.2);
    }
}

Greetings

10 years, 11 months ago.

I ran your code on an LPC1768, it works fine for me, both with the second attach at 5us and 50us. (I only connected it to LED2 instead of p5).