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:
25 Metro(unsigned long interval_millis, uint8_t autoreset = 0);
26
34 void interval(unsigned long interval_millis);
35
44 bool check();
45
54 bool checkWithoutReset() const;
55
62 void reset();
63
64private:
65 uint8_t autoreset;
66 unsigned long previous_millis;
67 unsigned long interval_millis;
68};
69
70inline Metro::Metro(unsigned long interval_millis, uint8_t autoreset)
71{
72 this->autoreset = autoreset; // Fix by Paul Bouchier
73 interval(interval_millis);
74 reset();
75}
76
77inline void Metro::interval(unsigned long interval_millis)
78{
79 this->interval_millis = interval_millis;
80}
81
82// Benjamin.soelberg's check behavior:
83// When a check is true, add the interval to the internal counter.
84// This should guarantee a better overall stability.
85
86// Original check behavior:
87// When a check is true, add the interval to the current millis() counter.
88// This method can add a certain offset over time.
89
90inline bool Metro::check()
91{
92 if (millis() - this->previous_millis >= this->interval_millis)
93 {
94 // As suggested by benjamin.soelberg@gmail.com, the following line
95 // this->previous_millis = millis();
96 // was changed to
97 // this->previous_millis += this->interval_millis;
98
99 // If the interval is set to 0 we revert to the original behavior
100 if (this->interval_millis <= 0 || this->autoreset)
101 {
102 this->previous_millis = millis();
103 }
104 else
105 {
106 this->previous_millis += this->interval_millis;
107 }
108
109 return 1;
110 }
111
112 return 0;
113}
114
115inline bool Metro::checkWithoutReset() const
116{
117 if (millis() - this->previous_millis >= this->interval_millis)
118 {
119 return 1;
120 }
121 return 0;
122}
123
125{
126
127 this->previous_millis = millis();
128}
Our own implementation of Metro class.
Definition metro.h:13
void reset()
Resets the timer to the current time.
Definition metro.h:124
bool checkWithoutReset() const
Checks if the interval has passed without resetting the timer.
Definition metro.h:115
Metro(unsigned long interval_millis, uint8_t autoreset=0)
Constructor to initialize the timer with a given interval and autoreset behavior.
Definition metro.h:70
bool check()
Checks if the interval has passed and resets the timer if true.
Definition metro.h:90
void interval(unsigned long interval_millis)
Sets a new interval for the timer.
Definition metro.h:77