-
Notifications
You must be signed in to change notification settings - Fork 0
/
RtcController.h
65 lines (62 loc) · 2.41 KB
/
RtcController.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
#include "Wire.h"
#define DS3231_I2C_ADDRESS 0x68
class RtcController {
public:
RtcController() {
Wire.begin();
}
void setTime(byte second, byte minute, byte hour, byte dayOfWeek, byte dayOfMonth, byte month, byte year) {
// sets time and date data to DS3231
Wire.beginTransmission(DS3231_I2C_ADDRESS);
Wire.write(0); // set next input to start at the seconds register
Wire.write(decToBcd(second)); // set seconds
Wire.write(decToBcd(minute)); // set minutes
Wire.write(decToBcd(hour)); // set hours
Wire.write(decToBcd(dayOfWeek)); // set day of week (1=Sunday, 7=Saturday)
Wire.write(decToBcd(dayOfMonth)); // set date (1 to 31)
Wire.write(decToBcd(month)); // set month
Wire.write(decToBcd(year)); // set year (0 to 99)
Wire.endTransmission();
}
byte getSecond( void ) {
byte second, minute, hour, dayOfWeek, dayOfMonth, month, year;
this->readTime(&second, &minute, &hour, &dayOfWeek, &dayOfMonth, &month, &year);
return second;
}
byte getMinute( void ) {
byte second, minute, hour, dayOfWeek, dayOfMonth, month, year;
this->readTime(&second, &minute, &hour, &dayOfWeek, &dayOfMonth, &month, &year);
return minute;
}
byte getHour( void ) {
byte second, minute, hour, dayOfWeek, dayOfMonth, month, year;
this->readTime(&second, &minute, &hour, &dayOfWeek, &dayOfMonth, &month, &year);
return hour;
}
private:
// Convert normal decimal numbers to binary coded decimal
byte decToBcd(byte val)
{
return( (val/10*16) + (val%10) );
}
// Convert binary coded decimal to normal decimal numbers
byte bcdToDec(byte val)
{
return( (val/16*10) + (val%16) );
}
void readTime(byte *second, byte *minute, byte *hour, byte *dayOfWeek, byte *dayOfMonth, byte *month, byte *year)
{
Wire.beginTransmission(DS3231_I2C_ADDRESS);
Wire.write(0); // set DS3231 register pointer to 00h
Wire.endTransmission();
Wire.requestFrom(DS3231_I2C_ADDRESS, 7);
// request seven bytes of data from DS3231 starting from register 00h
*second = bcdToDec(Wire.read() & 0x7f);
*minute = bcdToDec(Wire.read());
*hour = bcdToDec(Wire.read() & 0x3f);
*dayOfWeek = bcdToDec(Wire.read());
*dayOfMonth = bcdToDec(Wire.read());
*month = bcdToDec(Wire.read());
*year = bcdToDec(Wire.read());
}
}; //end rtc Controller