contrem / arduino-timer

Non-blocking library for delaying function calls
BSD 3-Clause "New" or "Revised" License
334 stars 50 forks source link

Is It possible to get time remaining until the end? #51

Closed sidneivl closed 3 years ago

sidneivl commented 3 years ago

Hi,

I appreciate your work and I would know if is possible to show the time remaining until the end.

For example, I have a countdown with a specific time using the function in(), but I want to show the time remaining in a display.

I tried use the function every() but in the looping the time is desynchronized because I have some delays.

An exemple of code to illustrate that.

`#include

auto t = timer_create_default();

int timerToShow = 60000; int timerToShowArduino = 60000;

long previousMillis = 0; const int maxTime = 1000;

bool counting = false;

bool updateTimer(void *) { timerToShow -= 1000; return true; }

void updateTimerByArduino() { timerToShowArduino -= 1000; }

bool finishTimer(void *) { Serial.println("finish"); counting = false; t.cancel(); return true; }

void setup() { Serial.begin(9600); Serial.println("start"); counting = true; t.in(timerToShow, finishTimer); t.every(1000, updateTimer); }

void loop() { if(millis() - previousMillis >= maxTime) { previousMillis = millis();

    t.tick();

    updateTimerByArduino();

    if(counting) {
      Serial.println(String(t.ticks()) + "|" + String(timerToShow) + "|" + String(timerToShowArduino));
    }

    delay(1500);

} }`

In this case when the call finishTimer() in the correct time, the counters are on 20000 yet.

Can you help me?

Regards

sidneivl commented 3 years ago

I've improved the code using Millis() but your lib have doesn't a function to do that?

void updateTimerByArduino() { timerToShowArduino += (timePast - millis()); timePast = millis(); }