Skip to content

Commit a6588e3

Browse files
committed
Merge branch 'mc/fix-tick-return'
* mc/fix-tick-return: timer:keywords: add ticks method README: document ticks() function src:arduino-timer: ticks() function src:arduino-timer: fix timer() return value
2 parents 9532adc + 0f1bdae commit a6588e3

File tree

3 files changed

+34
-3
lines changed

3 files changed

+34
-3
lines changed

README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,9 @@ every(unsigned long interval, handler_t handler, T opaque = T());
9999
100100
/* Cancel a timer task */
101101
void cancel(Timer<>::Task &task);
102+
103+
/* Returns the ticks until next event, or 0 if none */
104+
unsigned long ticks();
102105
```
103106

104107
### Installation

keywords.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ in KEYWORD2
1818
at KEYWORD2
1919
every KEYWORD2
2020
tick KEYWORD2
21+
ticks KEYWORD2
2122
cancel KEYWORD2
2223

2324
#######################################

src/arduino-timer.h

Lines changed: 30 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -100,8 +100,6 @@ class Timer {
100100
unsigned long
101101
tick()
102102
{
103-
unsigned long ticks = (unsigned long)-1;
104-
105103
for (size_t i = 0; i < max_tasks; ++i) {
106104
struct task * const task = &tasks[i];
107105

@@ -114,14 +112,43 @@ class Timer {
114112

115113
if (task->repeat) task->start = t;
116114
else remove(task);
115+
}
116+
}
117+
}
118+
119+
return ticks();
120+
}
121+
122+
/* Ticks until the next event */
123+
unsigned long
124+
ticks()
125+
{
126+
unsigned long ticks = (unsigned long)-1, elapsed;
127+
const unsigned long start = time_func();
128+
129+
for (size_t i = 0; i < max_tasks; ++i) {
130+
struct task * const task = &tasks[i];
131+
132+
if (task->handler) {
133+
const unsigned long t = time_func();
134+
const unsigned long duration = t - task->start;
135+
136+
if (duration >= task->expires) {
137+
ticks = 0;
138+
break;
117139
} else {
118140
const unsigned long remaining = task->expires - duration;
119141
ticks = remaining < ticks ? remaining : ticks;
120142
}
121143
}
122144
}
123145

124-
return ticks == (unsigned long)-1 ? 0 : ticks;
146+
elapsed = time_func() - start;
147+
148+
if (elapsed >= ticks || ticks == (unsigned long)-1) ticks = 0;
149+
else ticks -= elapsed;
150+
151+
return ticks;
125152
}
126153

127154
private:

0 commit comments

Comments
 (0)