RTC test

Never worked with it before, so time to give it a try. I will use it in a future project where I need to log sensor readings on an SD card. The code below will read the date/time from the DS1307 RTC module.

/*
   Check current RTC value.
   Created this to verify if the clock works like expected once initialized.

   The circuit:
   - DS1307 --> Arduino Uno
     - GND --> GND
     - VCC --> 5V
     - SDA --> A4
     - SCL --> A5

   Created 2017/09/24
   By Maarten Van Damme
   Modified
   By Maarten Van Damme

   http://projects.familievandamme.be
*/

#include <RTClib.h>

RTC_DS1307 RTC;

void setup() {
  Serial.begin(9600);
  while (!Serial) {
    ; //Just wait until connected to ensure all output is shown.
  }  
  RTC.begin();
  while (!RTC.isrunning()) {
    Serial.println(F("RTC is not running!"));
    delay(1000);
  }
}

void loop() {
  DateTime currentDateTime = RTC.now();
  char timestamp_YYYYMMDDHHMMSS[20];
  sprintf(timestamp_YYYYMMDDHHMMSS, "%04d/%02d/%02d %02d:%02d:%02d",
          currentDateTime.year(),
          currentDateTime.month(),
          currentDateTime.day(),
          currentDateTime.hour(),
          currentDateTime.minute(),
          currentDateTime.second());
  Serial.print(F("Current time: "));
  Serial.println(timestamp_YYYYMMDDHHMMSS);
  delay(1000);
}

As this was the first time I used the module, the date nor the time was correct. This can be corrected via the ‘adjust’ function of the RTC library.

RTC.adjust(DateTime(__DATE__, __TIME__));

Example:

/*
   Set RTC value to current (compilation) time.
   Only needs to be done once (or if the clock is getting out of sync, or if the battery was unplugged).

   The circuit:
   - DS1307 --> Arduino Uno
     - GND --> GND
     - VCC --> 5V
     - SDA --> A4
     - SCL --> A5

   Created 2017/09/24
   By Maarten Van Damme
   Modified
   By Maarten Van Damme

   http://projects.familievandamme.be
*/

#include <RTClib.h>

RTC_DS1307 RTC;

void setup() {
  Serial.begin(9600);
  RTC.begin();
  while (!Serial) {
    ; //Just wait until connected to ensure all output is shown.
  }
  while (!RTC.isrunning()) {
    Serial.println(F("RTC is not running!"));
    delay(1000);
  }
  RTC.adjust(DateTime(__DATE__, __TIME__));
}

void loop() {
}

 

Output:

1 comment

  1. Riani says:

    I liked this article.It was helpful. Keep on posting!

Leave a Reply

Your email address will not be published. Required fields are marked *