2013/07/28

Display Date and Time In Arduino Serial Monitor Using Time.h

First, Download Time.h from the following link.
http://playground.arduino.cc/uploads/Code/Time.zip

Read usage of Time.h library.
http://playground.arduino.cc/Code/time

The function is almost same as the sketch post on May 1, 2012, except adding displaying the day of week.

Pins Used

Analog pins 4.and 5 are used for I2C protocol implemented by Maxim DS1307.

Serial Monitor Output


Sketch

/*
 * TimeRTC.pde
 * example code illustrating Time library with Real Time Clock.
 * the sketch works on Arduino IDE 1.05
 * modified by Befun Horng on Jul. 28, 2013
 * changing the sequence to year, month, day, hour, minute, second
 * adding the day of week
 * almost same function as sketch on May 1, 2012
 */

#include <Time.h>
#include <Wire.h>
#include <DS1307RTC.h>  // a basic DS1307 library that returns time as a time_t
char *dayOfWeek[] = {"", "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
void setup()  {
  Serial.begin(9600);
  setSyncProvider(RTC.get);   // the function to get the time from the RTC
  if(timeStatus()!= timeSet)
     Serial.println("Unable to sync with the RTC");
  else
     Serial.println("RTC has set the system time");    
}

void loop()
{
   digitalClockDisplay();
   delay(1000);
}

void digitalClockDisplay(){
  // digital clock display of the time
  Serial.print(year());
  Serial.print("-");
  if (month() < 10) {
    Serial.print('0');
  }
  Serial.print(month());
  Serial.print("-");
  if (day() < 10) {
    Serial.print('0');
  }
  Serial.print(day());
  Serial.print(" ");
  Serial.print(dayOfWeek[weekday()]);
  Serial.print(' ');
  if (hour() < 10) {
    Serial.print('0');
  }
  Serial.print(hour());
  Serial.print(':');
  if (minute() < 10) {
    Serial.print('0');
  }
  Serial.print(minute());
  Serial.print(':');
  if (second() < 10) {
    Serial.print('0');
  }
  Serial.print(second());
  Serial.println();
}

No comments:

Post a Comment