1 // See tutotial: http://tronixlabs.com/news/tutorial-using-ds1307-and-ds3231-realtime-clock-modules-with-arduino/
4 #define DS3231_I2C_ADDRESS 0x68
5 // Convert normal decimal numbers to binary coded decimal
6 byte decToBcd(byte val)
8 return( (val/10*16) + (val%10) );
10 // Convert binary coded decimal to normal decimal numbers
11 byte bcdToDec(byte val)
13 return( (val/16*10) + (val%16) );
19 // set the initial time here:
20 // DS3231 seconds, minutes, hours, day, date, month, year
21 //setDS3231time(30,27,19,2,10,2,15); // Comment again after setting up
22 // or you will rset the clock at each upload
24 void setDS3231time(byte second, byte minute, byte hour, byte dayOfWeek, byte
25 dayOfMonth, byte month, byte year)
27 // sets time and date data to DS3231
28 Wire.beginTransmission(DS3231_I2C_ADDRESS);
29 Wire.write(0); // set next input to start at the seconds register
30 Wire.write(decToBcd(second)); // set seconds
31 Wire.write(decToBcd(minute)); // set minutes
32 Wire.write(decToBcd(hour)); // set hours
33 Wire.write(decToBcd(dayOfWeek)); // set day of week (1=Sunday, 7=Saturday)
34 Wire.write(decToBcd(dayOfMonth)); // set date (1 to 31)
35 Wire.write(decToBcd(month)); // set month
36 Wire.write(decToBcd(year)); // set year (0 to 99)
37 Wire.endTransmission();
39 void readDS3231time(byte *second,
47 Wire.beginTransmission(DS3231_I2C_ADDRESS);
48 Wire.write(0); // set DS3231 register pointer to 00h
49 Wire.endTransmission();
50 Wire.requestFrom(DS3231_I2C_ADDRESS, 7);
51 // request seven bytes of data from DS3231 starting from register 00h
52 *second = bcdToDec(Wire.read() & 0x7f);
53 *minute = bcdToDec(Wire.read());
54 *hour = bcdToDec(Wire.read() & 0x3f);
55 *dayOfWeek = bcdToDec(Wire.read());
56 *dayOfMonth = bcdToDec(Wire.read());
57 *month = bcdToDec(Wire.read());
58 *year = bcdToDec(Wire.read());
62 byte second, minute, hour, dayOfWeek, dayOfMonth, month, year;
63 // retrieve data from DS3231
64 readDS3231time(&second, &minute, &hour, &dayOfWeek, &dayOfMonth, &month,
66 // send it to the serial monitor
67 Serial.print(hour, DEC);
68 // convert the byte variable to a decimal number when displayed
74 Serial.print(minute, DEC);
80 Serial.print(second, DEC);
82 Serial.print(dayOfMonth, DEC);
84 Serial.print(month, DEC);
86 Serial.print(year, DEC);
87 Serial.print(" Day of week: ");
90 Serial.println("Sunday");
93 Serial.println("Monday");
96 Serial.println("Tuesday");
99 Serial.println("Wednesday");
102 Serial.println("Thursday");
105 Serial.println("Friday");
108 Serial.println("Saturday");
114 displayTime(); // display the real-time clock data on the Serial Monitor,
115 delay(1000); // every second