Skip to content

Commit 4e0fdcf

Browse files
committed
src:arduino-timer: fix timer() return value
Calculate the return value for tick() taking into account handler duration and repeating task expirations. The old calculation didn't consider the total elapsed time of all handlers, so the ticks returned could be wrong if their total elapsed time was greater than the expiration of the next task.
1 parent 721bfa2 commit 4e0fdcf

File tree

1 file changed

+12
-4
lines changed

1 file changed

+12
-4
lines changed

src/arduino-timer.h

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,8 @@ class Timer {
100100
unsigned long
101101
tick()
102102
{
103-
unsigned long ticks = (unsigned long)-1;
103+
unsigned long ticks = (unsigned long)-1, elapsed;
104+
const unsigned long start = time_func();
104105

105106
for (size_t i = 0; i < max_tasks; ++i) {
106107
struct task * const task = &tasks[i];
@@ -112,16 +113,23 @@ class Timer {
112113
if (duration >= task->expires) {
113114
task->repeat = task->handler(task->opaque) && task->repeat;
114115

115-
if (task->repeat) task->start = t;
116-
else remove(task);
116+
if (task->repeat) {
117+
task->start = t;
118+
ticks = task->expires < ticks ? task->expires : ticks;
119+
} else remove(task);
117120
} else {
118121
const unsigned long remaining = task->expires - duration;
119122
ticks = remaining < ticks ? remaining : ticks;
120123
}
121124
}
122125
}
123126

124-
return ticks == (unsigned long)-1 ? 0 : ticks;
127+
elapsed = time_func() - start;
128+
129+
if (elapsed >= ticks || ticks == (unsigned long)-1) ticks = 0;
130+
else ticks -= elapsed;
131+
132+
return ticks;
125133
}
126134

127135
private:

0 commit comments

Comments
 (0)