Ticker

The Ticker interface is used to setup a recurring interrupt to repeatedly call a function at a specified rate.

Any number of Ticker objects can be created, allowing multiple outstanding interrupts at the same time. The function can be a static function, or a member function of a particular object.

Hello World!

A simple program to setup a Ticker to invert an LED repeatedly...

// Example attaching a static function to a ticker

#include "mbed.h"

Ticker flipper;
DigitalOut led1(LED1);
DigitalOut led2(LED2);

void flip() {
    led2 = !led2;
}

int main() {
    led2 = 1;
    flipper.attach(&flip, 2.0); // the address of the function to be attached (flip) and the interval (2 seconds)

    // spin in a main loop. flipper will interrupt it to call flip
    while(1) {
        led1 = !led1;
        wait(0.2);
    }
}

API

TickerA Ticker is used to call a function at a recurring interval
Functions
attachAttach a function to be called by the Ticker, specifiying the interval in seconds
attachAttach a member function to be called by the Ticker, specifiying the interval in seconds
attach_usAttach a function to be called by the Ticker, specifiying the interval in micro-seconds
attach_usAttach a member function to be called by the Ticker, specifiying the interval in micro-seconds
detachDetach the function
class Ticker : public TimerEvent
A Ticker is used to call a function at a recurring interval
void attach(void (*fptr)(void),
float t)
Attach a function to be called by the Ticker, specifiying the interval in seconds
void attach_us(void (*fptr)(void),
unsigned int t)
Attach a function to be called by the Ticker, specifiying the interval in micro-seconds
void detach()
Detach the function

Examples

// Example attaching a member function to a ticker

#include "mbed.h"

// A class for flip()-ing a DigitalOut 
class Flipper {
public:
    Flipper(PinName pin) : _pin(pin) {
        _pin = 0;
    }
    void flip() {
        _pin = !_pin;
    }
private:
    DigitalOut _pin;
};

DigitalOut led1(LED1);
Flipper f(LED2);
Ticker t;

int main() {
    t.attach(&f, &Flipper::flip, 2.0); // the address of the object, member function, and interval

    // spin in a main loop. flipper will interrupt it to call flip
    while(1) {
        led1 = !led1;
        wait(0.2);
    }
}