Formula Student Electronics & Software
The code for the embedded software
Loading...
Searching...
No Matches
metro.h
Go to the documentation of this file.
1#pragma once
2
3#include "Arduino.h"
4#include <inttypes.h>
5
12class Metro
13{
14
15public:
16
26 Metro(unsigned long interval_millis, uint8_t autoreset = 0);
27
35 void interval(unsigned long interval_millis);
36
45 bool check();
46
55 bool checkWithoutReset() const;
56
63 void reset();
64
65private:
66 uint8_t autoreset;
67 unsigned long previous_millis;
68 unsigned long interval_millis;
69};
70
71inline Metro::Metro(unsigned long interval_millis, uint8_t autoreset)
72{
73 this->autoreset = autoreset; // Fix by Paul Bouchier
74 interval(interval_millis);
75 reset();
76}
77
78inline void Metro::interval(unsigned long interval_millis)
79{
80 this->interval_millis = interval_millis;
81}
82
83// Benjamin.soelberg's check behavior:
84// When a check is true, add the interval to the internal counter.
85// This should guarantee a better overall stability.
86
87// Original check behavior:
88// When a check is true, add the interval to the current millis() counter.
89// This method can add a certain offset over time.
90
91inline bool Metro::check()
92{
93 if (millis() - this->previous_millis >= this->interval_millis)
94 {
95 // As suggested by benjamin.soelberg@gmail.com, the following line
96 // this->previous_millis = millis();
97 // was changed to
98 // this->previous_millis += this->interval_millis;
99
100 // If the interval is set to 0 we revert to the original behavior
101 if (this->interval_millis <= 0 || this->autoreset)
102 {
103 this->previous_millis = millis();
104 }
105 else
106 {
107 this->previous_millis += this->interval_millis;
108 }
109
110 return 1;
111 }
112
113 return 0;
114}
115
116inline bool Metro::checkWithoutReset() const
117{
118 if (millis() - this->previous_millis >= this->interval_millis)
119 {
120 return 1;
121 }
122 return 0;
123}
124
126{
127
128 this->previous_millis = millis();
129}
Our own implementation of Metro class.
Definition metro.h:13
void reset()
Resets the timer to the current time.
Definition metro.h:125
bool checkWithoutReset() const
Checks if the interval has passed without resetting the timer.
Definition metro.h:116
Metro(unsigned long interval_millis, uint8_t autoreset=0)
Constructor to initialize the timer with a given interval and autoreset behavior.
Definition metro.h:71
bool check()
Checks if the interval has passed and resets the timer if true.
Definition metro.h:91
void interval(unsigned long interval_millis)
Sets a new interval for the timer.
Definition metro.h:78