forked from Nyarmith/clock
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTimeUtils.h
142 lines (121 loc) · 2.72 KB
/
TimeUtils.h
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
#include <RtcDS3231.h>
#include <Wire.h>
struct TimeRange
{
Time begin_;
Time end_;
TimeRange(Time start, Time stop) : begin_(start),end_(stop)
{
}
bool operator<(const Time &o)
{
o < begin_;
}
bool operator>(const Time &o)
{
o >= end_;
}
};
struct Time
{
uint8_t hours;
uint8_t mins;
uint8_t secs;
uint32_t micros;
operator<(const Time &o)
{
return Hour <= o.Hour && Min <= o.Min &&
Sec <= o.Sec && Min < o.Mil;
}
operator<=(const Time &o)
{
return Hour<=o.Hour && Min <= o.Min &&
Sec <= o.Sec && Min <= o.Mil;
}
operator>(const Time &o)
{
return Hour >= o.Hour && Min >= o.Min &&
Sec >= o.Sec && Min > o.Mil;
}
operator>=(const Time &o)
{
return Hour>=o.Hour && Min >= o.Min &&
Sec >= o.Sec && Min >= o.Mil;
}
void normalize()
{
while (micros >= 1000000)
{
micros -= 1000000;
++Sec;
while (secs >= 60)
{
++mins;
secs -= 60;
while (mins >= 60)
{
mins -= 60;
++hours;
while (hours >= 24)
{
hours -= 24;
}
}
}
}
}
void addMicros(uint32_t microseconds)
{
micros += microseconds;
normalize();
}
Time& operator+(const uint32_t microseconds)
{
addMicros(microseconds);
}
Time& operator+(const Time *time)
{
hours += time.hours;
mins += time.mins;
secs += time.secs;
micros += time.micros;
normalize();
}
};
class RTC_Interface
{
private:
RtcDS3231<TwoWire> Rtc{Wire};
constexpr uint32_t sync_timeout{60 * 1000000};
uint32_t last_sync_micros{0};
public:
void init(Time &time)
{
Rtc.Begin();
Rtc.Enable32kHzPin(false);
Rtc.SetSquareWavePin(DS3231SquareWavePin_ModeNone);
RtcDateTime now = Rtc.GetDateTime();
last_sync_micros = micros();
time.hours = now.Hour();
time.mins = now.Minute();
time.secs = now.Second();
time.micros = 0;
}
void update(Time &time)
{
uint32_t system_micros = micros();
if (system_micros - last_sync_micros > sync_timeout)
{
last_sync_micros = system_micros;
RtcDateTime now = Rtc.GetDateTime();
globTime.Hour = now.Hour();
globTime.Min = now.Minute();
globTime.Sec = now.Second();
}
timer -= dt;
if (timer < 0)
{
timer = timeout;
}
}
};