sstaub / Ticker

Ticker library for Arduino
MIT License
192 stars 37 forks source link

[Feature] Allow NULL callbacks and set state to STOPPED #22

Closed jj-uk closed 4 years ago

jj-uk commented 4 years ago

Please consider the following:

Set status = STOPPED; in the constructor. (otherwise it's used uninitialised.)

Allow NULL function pointers. This allows the timer to run, and be polled instead of calling the callback.

Remove all checks on callback:

// if (callback == NULL) return;

Change update to the following:

void Ticker::update() {
if (tick()) {
    if( callback ) callback();
}

Change both instances of:

if (repeat - counts == 1) {
    enabled = false;
}

to be as follows:

if ((repeat - counts) == 1) {
    enabled = false;
    status = STOPPED;
}

With the above changes implemented, a "blocking" delay(ms) routine can easily be coded without having to provide a dummy callback:

void DelayBlocked( uint32_t ms )
{
    Ticker t( NULL, ms, 1, MILLIS );
    t.start();
    do
    {
      t.update();
    } while( STOPPED != t.state() );
}

Without my suggested changes, a "blocking" delay(ms) routine looks like this:

void DelayBlocked( uint32_t ms )
{
    Ticker t( DummyCallback, ms, 1, MILLIS );
    t.start();
    do
    {
      t.update();
    } while( 1 != t.counter() );
}

void DummyCallback()
{
}
sstaub commented 4 years ago

For a blockig delay simply use delay()