Skip to content

Commit aecacac

Browse files
committed
src:arduino-timer: ticks() function
Split the ticks calculation into a separate function. Fixes issue of invalid tick value when adding a task from within a task. If the task ends up in an earlier slot, its expiration is not handled. Post-processing the ticks avoids the issue.
1 parent 4e0fdcf commit aecacac

File tree

1 file changed

+25
-6
lines changed

1 file changed

+25
-6
lines changed

src/arduino-timer.h

Lines changed: 25 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,29 @@ class Timer {
9999
/* Ticks the timer forward - call this function in loop() */
100100
unsigned long
101101
tick()
102+
{
103+
for (size_t i = 0; i < max_tasks; ++i) {
104+
struct task * const task = &tasks[i];
105+
106+
if (task->handler) {
107+
const unsigned long t = time_func();
108+
const unsigned long duration = t - task->start;
109+
110+
if (duration >= task->expires) {
111+
task->repeat = task->handler(task->opaque) && task->repeat;
112+
113+
if (task->repeat) task->start = t;
114+
else remove(task);
115+
}
116+
}
117+
}
118+
119+
return ticks();
120+
}
121+
122+
/* Ticks until the next event */
123+
unsigned long
124+
ticks()
102125
{
103126
unsigned long ticks = (unsigned long)-1, elapsed;
104127
const unsigned long start = time_func();
@@ -111,12 +134,8 @@ class Timer {
111134
const unsigned long duration = t - task->start;
112135

113136
if (duration >= task->expires) {
114-
task->repeat = task->handler(task->opaque) && task->repeat;
115-
116-
if (task->repeat) {
117-
task->start = t;
118-
ticks = task->expires < ticks ? task->expires : ticks;
119-
} else remove(task);
137+
ticks = 0;
138+
break;
120139
} else {
121140
const unsigned long remaining = task->expires - duration;
122141
ticks = remaining < ticks ? remaining : ticks;

0 commit comments

Comments
 (0)