Skip to content

PeriodicTimer

class PeriodicTimer; // namespace TeensyTimerTool

A PeriodicTimer invokes its callback at a fixed interval. The functions common to all timers (start(), stop(), end(), setPrescaler(), the getters, copying and moving) are described in Common functions.


PeriodicTimer()

PeriodicTimer(TimerGenerator* timerType = nullptr);

Creates a timer object. No hardware is allocated yet: begin() takes a channel of the given timer type, or, without a timer type, the next free timer from the timer pool.

Parameter
timerType the timer type, e.g. PIT, TMR1, TCK; see Timer types. nullptr (default): timer pool
PeriodicTimer t1;      // timer pool
PeriodicTimer t2(PIT); // a PIT channel

begin()

template <typename period_t>
errorCode begin(callback_t callback, period_t period, bool start = true);

Allocates a timer channel (on the first call), sets the callback and the period and starts the timer. Called on a running timer, begin() restarts it with the new callback and period; the previous callback is no longer invoked.

begin() is a template so that the period can be passed in different types: as integer or floating point number (microseconds) or as std::chrono duration. The compiler deduces period_t from the argument.

t1.begin(onTimer, 1000);                                 // every 1000 µs
t1.begin(onTimer, 2.5ms);                                // every 2.5 ms
t1.begin([] { digitalToggleFast(LED_BUILTIN); }, 250ms); // lambda expression as callback
t1.begin(onTimer, 1s, false);                            // configured, started later with start()
Parameter
callback the function to invoke, see Callbacks
period the period, in microseconds or as std::chrono duration. Rounded to the nearest number of timer ticks, at least one tick
start true (default): start the timer; false: only configure it, start() starts it
Return value Condition
OK the timer runs (or is configured, with start = false)
periodOverflow (warning) period is longer than getMaxPeriod(); the timer runs with the maximum period
prescalerIgnored (warning) setPrescaler() was called before begin() on a timer type without prescaler; the timer runs
invalidArgument period is negative; or setPrescaler() was called before with an invalid value, in this case the timer runs with the default prescaler
noCallback callback is empty (nullptr)
zeroPeriod period is 0
noFreeChannel all channels of the requested timer type are in use
poolExhausted timer pool: no free timer left

Except where noted, the timer is unchanged after an error; a running timer keeps its callback and period.

Supported timers: all.


setPeriod()

template <typename period_t>
errorCode setPeriod(period_t period, PeriodMode mode = PeriodMode::restart);

Changes the period of the timer.

  • PeriodMode::restart (default): the new period starts at the call; the next callback occurs one new period after the call.
  • PeriodMode::keepElapsed: the time elapsed in the current period counts towards the new period. If it already exceeds the new period, the callback occurs immediately. The following periods have the new length.

A stopped timer stays stopped; start() starts it with the new period.

As in begin(), the template parameter period_t allows passing the period as integer or floating point number (microseconds) or as std::chrono duration.

t1.setPeriod(100);                            // 100 µs, starting now
t1.setPeriod(5ms);                            // 5 ms, starting now
t1.setPeriod(5ms, PeriodMode::keepElapsed);   // 5 ms, counted from the previous callback
Parameter
period the new period, in microseconds or as std::chrono duration. Rounded to the nearest number of timer ticks, at least one tick
mode PeriodMode::restart (default) or PeriodMode::keepElapsed
Return value Condition
OK the new period is set
periodOverflow (warning) period is longer than getMaxPeriod(); the maximum period is used
invalidArgument period is negative; the timer is unchanged
zeroPeriod period is 0; the timer is unchanged
notInitialized called before begin()
notSupported the timer doesn't support setPeriod() or the given mode; the timer is unchanged

Supported timers: restart: all Teensy 4 timers and the TCK timers. keepElapsed: PIT, TMR1 … TMR4, TCK, TCK64, TCK_RTC. Not supported: FTM0 … FTM3 (Teensy 3); keepElapsed on GPT1, GPT2, RTC.

Notes

  • The RTC timer synchronizes its periods with the clock: after setPeriod(), the next callback occurs within one period, not exactly one period after the call.
  • Changed in v1.5: up to v1.4, setPeriod() of the TMR and TCK timers behaved like PeriodMode::keepElapsed.

See also: setNextPeriod(), Changing the period.


setNextPeriod()

template <typename period_t>
errorCode setNextPeriod(period_t period);

Sets the period that starts when the current period ends. The current period is not changed: the next callback occurs as scheduled, the callbacks after it at the new interval.

Called from the callback, setNextPeriod() generates exact period sequences, since the new value is in place long before the current period ends. If it is called several times during one period, the last value is used. The template parameter period_t has the same purpose as in begin().

t1.setNextPeriod(300);   // 300 µs, after the current period has ended
t1.setNextPeriod(0.7ms);
Parameter
period the new period, in microseconds or as std::chrono duration. Rounded to the nearest number of timer ticks, at least one tick
Return value Condition
OK the new period is set
periodOverflow (warning) period is longer than getMaxPeriod(); the maximum period is used
invalidArgument period is negative; the timer is unchanged
zeroPeriod period is 0; the timer is unchanged
notInitialized called before begin()
notSupported the timer doesn't support setNextPeriod(); the timer is unchanged

Supported timers: PIT, TMR1 … TMR4, TCK, TCK64, TCK_RTC. Not supported: GPT1, GPT2, RTC (Teensy 4), FTM0 … FTM3 (Teensy 3).

Notes

  • getPeriod() returns the new period immediately after the call, i.e. the latest period set, not the period currently running.
  • On a stopped timer, setNextPeriod() works like setPeriod(): the timer stays stopped, and start() starts it with the new period.
  • setNextPeriod() can be called from the timer's own callback.

See also: setPeriod(), Changing the period at the end of the current period (example: alternating periods).


resume()

errorCode resume();

Continues a timer stopped with stop() with the rest of the interrupted period, as if it had not been stopped: the time while stopped doesn't count. The following periods are unchanged. In contrast, start() restarts the period.

t1.begin(onTimer, 10ms);
// ...
t1.stop();   // e.g. 3 ms into the period
// ...
t1.resume(); // next callback 7 ms from now, then every 10 ms
Return value Condition
OK the timer runs
notInitialized called before begin()
notSupported the timer doesn't support resume(); the timer is unchanged

Supported timers: PIT, GPT1, GPT2, TMR1 … TMR4, TCK, TCK64, TCK_RTC. Not supported: RTC (Teensy 4), FTM0 … FTM3 (Teensy 3).

Notes

  • Without an interrupted period, resume() works like start(): after begin(callback, period, false), or if start() or begin() was called after stop(). On a running timer, it has no effect.
  • Period changes while the timer is stopped take effect as on a running timer: after setPeriod(), resume() starts the new period; after setNextPeriod(), the new period follows the rest of the interrupted period.

getPeriod()

template <typename T = float>
T getPeriod() const;

Returns the period set by the latest begin(), setPeriod() or setNextPeriod(), rounded as the timer uses it: e.g. 99.84 µs for a TMR timer started with 100 µs, the maximum period after an overflow. After setPrescaler() on a running timer, it returns the period resulting from the new prescaler. The template parameter selects the unit of the result, see Getters with units.

float seconds = t1.getPeriod();                           // e.g. 0.00009984
auto  micros  = t1.getPeriod<std::chrono::microseconds>(); // e.g. 100 µs
Template parameter
T float (default) or double: seconds; or a std::chrono duration, e.g. std::chrono::microseconds. Integer durations are rounded to the nearest unit
Return value Condition
the period
NAN / T::zero(), reports notInitialized called before begin()
NAN / T::zero(), reports notSupported the timer doesn't support getPeriod()

Supported timers: all Teensy 4 timers, TCK, TCK64. Not supported: FTM0 … FTM3 (Teensy 3).