-
Notifications
You must be signed in to change notification settings - Fork 20
/
timer.cpp
108 lines (90 loc) · 1.83 KB
/
timer.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
#include "timer.h"
#include "timerManager.h"
Timer::Timer() {
initial_time = 0;
current_time = 0;
interval = 0;
last_interval_time = 0;
repeat_count = -1;
is_running = false;
is_paused = false;
interval_is_setted = false;
function_callback = NULL;
TimerManager::instance().add(this);
}
Timer::~Timer() {
TimerManager::instance().remove(this);
}
void Timer::start() {
if(isPaused()) {
int paused_time = millis() - current_time;
current_time = millis();
initial_time += paused_time;
last_interval_time += paused_time;
} else {
reset();
repeat_count = total_repeat_count;
}
is_running = true;
is_paused = false;
}
void Timer::stop() {
is_running = false;
is_paused = false;
}
void Timer::pause() {
is_running = false;
is_paused = true;
}
void Timer::reset() {
initial_time = millis();
current_time = initial_time;
last_interval_time = initial_time;
}
bool Timer::isPaused() {
return is_paused;
}
bool Timer::isStopped() {
return !is_paused && !is_running;
}
bool Timer::isRunning() {
return is_running;
}
unsigned long Timer::getElapsedTime() {
return current_time - initial_time;
}
void Timer::update() {
if(is_running) {
current_time = millis();
if(interval_is_setted) {
if(current_time - last_interval_time >= interval) {
call();
if(repeat_count > 0) {
repeat_count -= 1;
}
if(repeat_count == 0) {
stop();
return;
}
last_interval_time = current_time;
}
}
}
}
void Timer::setInterval(unsigned long interval, int repeat_count){
this->interval = interval;
this->repeat_count = repeat_count;
total_repeat_count = repeat_count;
interval_is_setted = true;
}
void Timer::setTimeout(unsigned long timeout){
setInterval(timeout, 1);
}
void Timer::clearInterval() {
repeat_count = -1;
}
void Timer::call() {
if(function_callback != NULL) {
function_callback();
}
}