Ticker
Ticker class hierarchy
Use the Ticker interface to set up a recurring interrupt; it calls a function repeatedly and at a specified rate.
You can create any number of Ticker objects, allowing multiple outstanding interrupts at the same time. The function can be a static function, a member function of a particular object or a Callback object.
Warnings and notes
-
No blocking code in ISR: avoid any call to wait, infinite while loop or blocking calls in general.
-
No printf, malloc or new in ISR: avoid any call to bulky library functions. In particular, certain library functions (such as printf, malloc and new) are not re-entrant, and their behavior could be corrupted when called from an ISR.
-
While an event is attached to a Ticker, deep sleep is blocked to maintain accurate timing. If you don't need microsecond precision, consider using the LowPowerTicker class instead because that does not block deep sleep mode.
Ticker class reference
Public Member Functions | |
template<typename F > | |
MBED_FORCEINLINE void | attach (F &&func, float t) |
Attach a function to be called by the Ticker, specifying the interval in seconds. More... | |
void | attach (Callback< void()> func, std::chrono::microseconds t) |
Attach a function to be called by the Ticker, specifying the interval in microseconds. More... | |
void | attach_us (Callback< void()> func, us_timestamp_t t) |
Attach a function to be called by the Ticker, specifying the interval in microseconds. More... | |
void | detach () |
Detach the function. More... |
Ticker hello, world
Try this program to set up a Ticker to repeatedly invert an LED:
/*
* Copyright (c) 2006-2020 Arm Limited and affiliates.
* SPDX-License-Identifier: Apache-2.0
*/
#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;
ThisThread::sleep_for(200);
}
}
Ticker examples
Use this example to attach a member function to a ticker:
/*
* Copyright (c) 2006-2020 Arm Limited and affiliates.
* SPDX-License-Identifier: Apache-2.0
*/
#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()
{
// the address of the object, member function, and interval
t.attach(callback(&f, &Flipper::flip), 2.0);
// spin in a main loop. flipper will interrupt it to call flip
while (1) {
led1 = !led1;
ThisThread::sleep_for(200);
}
}