Guest User

RTC 3231

a guest
Oct 5th, 2018
170
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Date and time functions using a DS3231 RTC connected via I2C and Wire lib
  2. #include <Wire.h>
  3. #include "RTClib.h"
  4.  
  5. RTC_DS3231 rtc;
  6.  
  7. char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
  8.  
  9. void setup () {
  10.  
  11. #ifndef ESP8266
  12.   while (!Serial); // for Leonardo/Micro/Zero
  13. #endif
  14.  
  15.   Serial.begin(9600);
  16.  
  17.   delay(3000); // wait for console opening
  18.  
  19.   if (! rtc.begin()) {
  20.     Serial.println("Couldn't find RTC");
  21.     while (1);
  22.   }
  23.  
  24.   if (rtc.lostPower()) {
  25.     Serial.println("RTC lost power, lets set the time!");
  26.     // following line sets the RTC to the date & time this sketch was compiled
  27.     rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
  28.     // This line sets the RTC with an explicit date & time, for example to set
  29.     // January 21, 2014 at 3am you would call:
  30.     // rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0));
  31.   }
  32. }
  33.  
  34. void loop () {
  35.     DateTime now = rtc.now();
  36.    
  37.     Serial.print(now.year(), DEC);
  38.     Serial.print('/');
  39.     Serial.print(now.month(), DEC);
  40.     Serial.print('/');
  41.     Serial.print(now.day(), DEC);
  42.     Serial.print(" (");
  43.     Serial.print(daysOfTheWeek[now.dayOfTheWeek()]);
  44.     Serial.print(") ");
  45.     Serial.print(now.hour(), DEC);
  46.     Serial.print(':');
  47.     Serial.print(now.minute(), DEC);
  48.     Serial.print(':');
  49.     Serial.print(now.second(), DEC);
  50.     Serial.println();
  51.    
  52.     Serial.print(" since midnight 1/1/1970 = ");
  53.     Serial.print(now.unixtime());
  54.     Serial.print("s = ");
  55.     Serial.print(now.unixtime() / 86400L);
  56.     Serial.println("d");
  57.    
  58.     // calculate a date which is 7 days and 30 seconds into the future
  59.     DateTime future (now + TimeSpan(7,12,30,6));
  60.    
  61.     Serial.print(" now + 7d + 30s: ");
  62.     Serial.print(future.year(), DEC);
  63.     Serial.print('/');
  64.     Serial.print(future.month(), DEC);
  65.     Serial.print('/');
  66.     Serial.print(future.day(), DEC);
  67.     Serial.print(' ');
  68.     Serial.print(future.hour(), DEC);
  69.     Serial.print(':');
  70.     Serial.print(future.minute(), DEC);
  71.     Serial.print(':');
  72.     Serial.print(future.second(), DEC);
  73.     Serial.println();
  74.    
  75.     Serial.println();
  76.     delay(3000);
  77. }
Add Comment
Please, Sign In to add comment