Problem with time library

Hallo ppl…

This is my first post and im verry new to arduino and everyting…

I got an arduino uno and was wondering the following…

If i want to display the time on an lcd do i have to get a real time clock??

I am also having trouble with the time library, I saved it in the library folder and can see it when i go to the examples.
If i open the library it gives me all the code but as soon as i try to compile it gives errors like: ‘time_t’ does not name a type

I have got 0022 installed

Thanks for any help…

Did you include it in your code? :stuck_out_tongue:


See my posts on time and the RTC here.,51802.0.html

No you don't need an RTC but considering it is $20 (CDN or US) and is much better than the alternative...

This one needs 5V

Which Arduino? Does it have both 3.3V and 5V output?

When using this (copy and pasting it in arduino) it still says ‘time_t’ does not name a type


  • Modified by D Robinson Feb 09, 2011

  • Time_NTP_UDP_DS1307.pde
  • Example showing time sync to NTP time source for V022 of Compiler and Time Libray
  • This sketch uses the Ethenet library with the current UDP library. **** Note ****
  • Also, the time is retrieved from the NTP Packet, then used to update the DS1307 RTC
  • The DS1307 RTC is then used to synchronize the clock in the Time Library.
  • Now that the clock is synched, you can just use a simpler RTC/Time Lib synch to retrieve
  • the time e.g. now() in your sketches.
  • Considering the drift on the DS1307 RTC you should probably synch every day or two.
  • If you add the new libraries you can also access the square wave generator through set2(time, sqvalue)
  • See the setup function below for an example…
  • You only need to run this occasionally to sync to network time standards.


#include <Time.h>
#include <SPI.h>
#include <Ethernet.h>

#include <Udp.h>

#include <WProgram.h>;
#include <Wire.h>
#include <DS1307RTC.h>


  • You may need to modify the Udp library to allow enough space in the buffers for the NTP packets.
  • Open up UdpBytewse.h and set the following buffers to 64 bytes:
  • #define UDP_TX_PACKET_MAX_SIZE 64
  • #define UDP_RX_PACKET_MAX_SIZE 64

byte mac = {
0x90, 0xA2, 0xDA, 0x00, 0x27, 0x7A };
byte ip = {
192,168,0,80 };

unsigned int localPort = 8888; // local port to listen for UDP packets

byte SNTP_server_IP = { 192, 43, 244, 18}; //

// byte SNTP_server_IP = { 132,246,11,227}; // weird time 64ms RT time
//byte SNTP_server_IP = { 130,149,17,21}; //
//byte SNTP_server_IP = { 192,53,103,108}; //

time_t prevDisplay = 0; // when the digital clock was displayed
time_t yy;
uint8_t zz;

unsigned long xx;

long HoursOffset = -5;
long SecondsInMinute = 60;
long MinutesInHour =60;
long timeZoneOffset; // set this to the offset in seconds to your local time;
long correctionfactor = 1;
const int NTP_PACKET_SIZE= 48; // NTP time stamp is in the first 48 bytes of the message

byte packetBuffer[ NTP_PACKET_SIZE]; //buffer to hold incoming and outgoing packets

void setup()

Serial.println(“waiting for sync – tzo”);
timeZoneOffset = (HoursOffset * MinutesInHour * SecondsInMinute);
// no delays in this group…

yy= getNtpTime();
zz= 0x91;
/* RTC.set2 adds the Square Wave Generator setup

0x90 sets to one blip a second
0x91 sets the oscilator to a 4,096 KHz Square Wave
0x92 sets the oscillator to a 8,192 KHz Sq. Wv.
0x93 sets the oscillator to a 32768 KHz Sq. Wv. (XTAL Frequncy)

// RTC.set2(yy,zz); // use this function with the modified libraries to set RTC
RTC.set(yy); //use this function with unmodified libraries to Set RTC

/* Now that we have set RTC with the NTP signal – we can sych the software timer
using setSyncProvider.
This will allow us to turn off the Arduino, and the load other programs
which only need to sync to the RTC – and don’t have to update to an
NTP server – unless you want the most accurate time.
If you believe the clock is drifiting – run this program as appropriate
or include the functionality on you program.
while(timeStatus()== timeNotSet); // wait until the time is set by the sync provider


void loop()
if( now() != prevDisplay) //update the display only if the time has changed
prevDisplay = now();

void digitalClockDisplay(){
// digital clock display of the time
Serial.print(" “);
Serial.print(” “);
Serial.print(” ");

void printDigits(int digits){
// utility function for digital clock display: prints preceding colon and leading 0
if(digits < 10)

/-------- NTP code ----------/

unsigned long getNtpTime()
delay(1000);// this delay is required…

if ( Udp.available() ) {
Udp.readPacket(packetBuffer,NTP_PACKET_SIZE); // read the packet into the buffer

//the timestamp starts at byte 40 of the received packet and is four bytes,
// or two words, long. First, esxtract the two words:

unsigned long highWord = word(packetBuffer[40], packetBuffer[41]);
unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]);
// combine the four bytes (two words) into a long integer
// this is NTP time (seconds since Jan 1 1900):
unsigned long secsSince1900 = highWord << 16 | lowWord;

// now convert NTP time into everyday time:
const unsigned long seventy_years = 2208988800UL; // subtract seventy years:
unsigned long epoch = secsSince1900 - seventy_years;
epoch = epoch + timeZoneOffset + correctionfactor; //do this here or we get apparent over/under flow
return epoch;
return 0; // return 0 if unable to get the time

unsigned long sendNTPpacket(byte *address)
// set all bytes in the buffer to 0
Serial.println(“Sending packet to server…”);
memset(packetBuffer, 0, NTP_PACKET_SIZE);
// Initialize values needed to form NTP request
// (see URL above for details on the packets)
packetBuffer[0] = 0b11100011; // LI, Version, Mode
packetBuffer[1] = 0; // Stratum, or type of clock
packetBuffer[2] = 6; // Polling Interval
packetBuffer[3] = 0xEC; // Peer Clock Precision
// 8 bytes of zero for Root Delay & Root Dispersion
packetBuffer[12] = 49;
packetBuffer[13] = 0x4E;
packetBuffer[14] = 49;
packetBuffer[15] = 52;

// all NTP fields have been given values, now
// you can send a packet requesting a timestamp:
Udp.sendPacket( packetBuffer,NTP_PACKET_SIZE, address, 123); //NTP requests are to port 123


yes its got 3.3 and 5v

I just ordered an RTC but I still need the code to compile..........


I just compiled the code successfully. When I did all of this work, I started with all the base libraries and so on from the places in the links. Then I modified and tested the Libraries. I can only assume that you are missing a “base reference” somewhere.

When you post code use the “#” link above and paste code between the two hashes. It eats up far less screen space and allows you to scroll through the code while still able to read the post…

You do have to update time.cpp and time .lib and the ds1307 lib… (The DS1307 Library must be present – mine has significant modifications.)

Note that the proper time.h does have the definition… just search for it a few lines down…

You need to make sure that you have the Time Lib installed or it WON’T compile – that’s the way it is. The Time Lib is in a directory under Libraries in the Arduino directory… it is called Time

As long as you install the original library first, then you will have all the example programs. Or you can just copy in the ones I supplied under an examples directory.

It contains Time.h, Time.cpp, DateStrings.cpp and keywords.txt – all four are required. All four were in the link I supplied…

If you PM me with an email I can zip the entire library and send it to you. It is quite small as a zipped file. The additional examples are all on the link to the “other Program Development” area.

The additions I made allow the expanded DS1307 access – to the square wave generator and the on-board memory NVSRAM – all consistent with the original time library.

Your frustration seems like mine when I started this project in mid-January. I do understand. lol

It just takes a week or so to fall in with the Arduino systems and it all starts to make sense – or else you go crazy and that’s why it makes sense --I am still not sure.

  time.h - low level time and date functions
  modified by D, Robinson Feb10, 2011 -- added access to square wave control byte
  see tmSQControl for example...
  and this below...
  uint8_t SQControl; // see DS1307 Sheet dwr feb10/2011  ** added tmSQControl above

#ifndef _Time_h
#define _Time_h

#include <inttypes.h>

typedef unsigned long time_t;

typedef enum {timeNotSet, timeNeedsSync, timeSet
}  timeStatus_t ;

typedef enum {
    dowInvalid, dowSunday, dowMonday, dowTuesday, dowWednesday, dowThursday, dowFriday, dowSaturday
} timeDayOfWeek_t;

typedef enum {
    tmSecond, tmMinute, tmHour, tmWday, tmDay,tmMonth, tmYear, tmSQControl,tmNbrFields
} tmByteFields;	   

typedef struct  { 
  uint8_t Second; 
  uint8_t Minute; 
  uint8_t Hour; 
  uint8_t Wday;   // day of week, sunday is day 1
  uint8_t Day;
  uint8_t Month; 
  uint8_t Year;   // offset from 1970;
  uint8_t SQControl; // see DS1307 Sheet dwr feb10/2011  ** added tmSQControl above
} 	tmElements_t, TimeElements, *tmElementsPtr_t;

//convenience macros to convert to and from tm years 
#define  tmYearToCalendar(Y) ((Y) + 1970)  // full four digit year 
#define  CalendarYrToTm(Y)   ((Y) - 1970)
#define  tmYearToY2k(Y)      ((Y) - 30)    // offset is from 2000
#define  y2kYearToTm(Y)      ((Y) + 30)   

typedef time_t(*getExternalTime)();
//typedef void  (*setExternalTime)(const time_t); // not used in this version

/* Useful Constants */
#define SECS_PER_MIN  (60UL)
#define SECS_PER_HOUR (3600UL)
#define DAYS_PER_WEEK (7UL)
#define SECS_YR_2000  (946684800UL) // the time at the start of y2k
/* Useful Macros for getting elapsed time */
#define numberOfSeconds(_time_) (_time_ % SECS_PER_MIN)  
#define numberOfMinutes(_time_) ((_time_ / SECS_PER_MIN) % SECS_PER_MIN) 
#define numberOfHours(_time_) (( _time_% SECS_PER_DAY) / SECS_PER_HOUR)
#define dayOfWeek(_time_)  ((( _time_ / SECS_PER_DAY + 4)  % DAYS_PER_WEEK)+1) // 1 = Sunday
#define elapsedDays(_time_) ( _time_ / SECS_PER_DAY)  // this is number of days since Jan 1 1970
#define elapsedSecsToday(_time_)  (_time_ % SECS_PER_DAY)   // the number of seconds since last midnight 
#define previousMidnight(_time_) (( _time_ / SECS_PER_DAY) * SECS_PER_DAY)  // time at the start of the given day
#define nextMidnight(_time_) ( previousMidnight(_time_)  + SECS_PER_DAY ) // time at the end of the given day 
#define elapsedSecsThisWeek(_time_)  (elapsedSecsToday(_time_) +  (dayOfWeek(_time_) * SECS_PER_DAY) )   

/* Useful Macros for converting elapsed time to a time_t */
#define minutesToTime_t ((M)) ( (M) * SECS_PER_MIN)  
#define hoursToTime_t   ((H)) ( (H) * SECS_PER_HOUR)  
#define daysToTime_t    ((H)) ( (D) * SECS_PER_DAY) 
#define weeksToTime_t   ((W)) ( (W) * SECS_PER_WEEK)   

/*  time and date functions   */
int     hour();            // the hour now 
int     hour(time_t t);    // the hour for the given time
int     hourFormat12();    // the hour now in 12 hour format
int     hourFormat12(time_t t); // the hour for the given time in 12 hour format
uint8_t isAM();            // returns true if time now is AM
uint8_t isAM(time_t t);    // returns true the given time is AM
uint8_t isPM();            // returns true if time now is PM
uint8_t isPM(time_t t);    // returns true the given time is PM
int     minute();          // the minute now 
int     minute(time_t t);  // the minute for the given time
int     second();          // the second now 
int     second(time_t t);  // the second for the given time
int     day();             // the day now 
int     day(time_t t);     // the day for the given time
int     weekday();         // the weekday now (Sunday is day 1) 
int     weekday(time_t t); // the weekday for the given time 
int     month();           // the month now  (Jan is month 1)
int     month(time_t t);   // the month for the given time
int     year();            // the full four digit year: (2009, 2010 etc) 
int     year(time_t t);    // the year for the given time

time_t now();              // return the current time as seconds since Jan 1 1970 
void    setTime(time_t t);
void    setTime(int hr,int min,int sec,int day, int month, int yr);
void    adjustTime(long adjustment);

/* date strings */ 
#define dt_MAX_STRING_LEN 9 // length of longest date string (excluding terminating null)
char* monthStr(uint8_t month);
char* dayStr(uint8_t day);
char* monthShortStr(uint8_t month);
char* dayShortStr(uint8_t day);
/* time sync functions	*/
timeStatus_t timeStatus(); // indicates if time has been set and recently synchronized
void    setSyncProvider( getExternalTime getTimeFunction); // identify the external time provider
void    setSyncInterval(time_t interval); // set the number of seconds between re-sync

/* low level functions to convert to and from system time                     */
void breakTime(time_t time, tmElements_t &tm);  // break time_t into elements
time_t makeTime(tmElements_t &tm);  // convert time elements into time_t

#endif /* _Time_h */

Here is the time.cpp for clarity…

  time.c - low level time and date functions
  Copyright (c) Michael Margolis 2009

  This library is free software; you can redistribute it and/or
  modify it under the terms of the GNU Lesser General Public
  License as published by the Free Software Foundation; either
  version 2.1 of the License, or (at your option) any later version.

  This library is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  Lesser General Public License for more details.

  You should have received a copy of the GNU Lesser General Public
  License along with this library; if not, write to the Free Software
  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
  10 February 2011 -- Time.h Modified by D. Robinson to add access to Square Wave Byte... on DS1307 RTC
     Probably only the Header was modified -- but noted here for clarity
     DS1307 RTC lib modifies as well

  6  Jan 2010 - initial release 
  12 Feb 2010 - fixed leap year calculation error
  1  Nov 2010 - fixed setTime bug (thanks to Korman for this)

#include <WProgram.h> 

#include "Time.h"

static tmElements_t tm;          // a cache of time elements
static time_t       cacheTime;   // the time the cache was updated
static time_t       syncInterval = 300;  // time sync will be attempted after this many seconds

void refreshCache( time_t t){
  if( t != cacheTime)
    breakTime(t, tm); 
    cacheTime = t; 

int hour() { // the hour now 
  return hour(now()); 

int hour(time_t t) { // the hour for the given time
  return tm.Hour;  

int hourFormat12() { // the hour now in 12 hour format
  return hourFormat12(now()); 

int hourFormat12(time_t t) { // the hour for the given time in 12 hour format
  if( tm.Hour == 0 )
    return 12; // 12 midnight
  else if( tm.Hour  > 12)
    return tm.Hour - 12 ;
    return tm.Hour ;

uint8_t isAM() { // returns true if time now is AM
  return !isPM(now()); 

uint8_t isAM(time_t t) { // returns true if given time is AM
  return !isPM(t);  

uint8_t isPM() { // returns true if PM
  return isPM(now()); 

uint8_t isPM(time_t t) { // returns true if PM
  return (hour(t) >= 12); 

int minute() {
  return minute(now()); 

int minute(time_t t) { // the minute for the given time
  return tm.Minute;  

int second() {
  return second(now()); 

int second(time_t t) {  // the second for the given time
  return tm.Second;

int day(){

int day(time_t t) { // the day for the given time (0-6)
  return tm.Day;

int weekday() {   // Sunday is day 1
  return  weekday(now()); 

int weekday(time_t t) {
  return tm.Wday;
int month(){
  return month(now()); 

int month(time_t t) {  // the month for the given time
  return tm.Month;

int year() {  // as in Processing, the full four digit year: (2009, 2010 etc) 
  return year(now()); 

int year(time_t t) { // the year for the given time
  return tmYearToCalendar(tm.Year);

/* functions to convert to and from system time */
/* These are for interfacing with time serivces and are not normally needed in a sketch */

// leap year calulator expects year argument as years offset from 1970
#define LEAP_YEAR(Y)     ( ((1970+Y)>0) && !((1970+Y)%4) && ( ((1970+Y)%100) || !((1970+Y)%400) ) )

static  const uint8_t monthDays[]={31,28,31,30,31,30,31,31,30,31,30,31}; // API starts months from 1, this array starts from 0
void breakTime(time_t time, tmElements_t &tm){
// break the given time_t into time components
// this is a more compact version of the C library localtime function
// note that year is offset from 1970 !!!

  uint8_t year;
  uint8_t month, monthLength;
  unsigned long days;
  tm.Second = time % 60;
  time /= 60; // now it is minutes
  tm.Minute = time % 60;
  time /= 60; // now it is hours
  tm.Hour = time % 24;
  time /= 24; // now it is days
  tm.Wday = ((time + 4) % 7) + 1;  // Sunday is day 1 
  year = 0;  
  days = 0;
  while((unsigned)(days += (LEAP_YEAR(year) ? 366 : 365)) <= time) {
  tm.Year = year; // year is offset from 1970 
  days -= LEAP_YEAR(year) ? 366 : 365;
  time  -= days; // now it is days in this year, starting at 0
  for (month=0; month<12; month++) {
    if (month==1) { // february
      if (LEAP_YEAR(year)) {
      } else {
    } else {
      monthLength = monthDays[month];
    if (time >= monthLength) {
      time -= monthLength;
    } else {
  tm.Month = month + 1;  // jan is month 1  
  tm.Day = time + 1;     // day of month

time_t makeTime(tmElements_t &tm){   
// assemble time elements into time_t 
// note year argument is offset from 1970 (see macros in time.h to convert to other formats)
// previous version used full four digit year (or digits since 2000),i.e. 2009 was 2009 or 9
  int i;
  time_t seconds;

  // seconds from 1970 till 1 jan 00:00:00 of the given year
  seconds= tm.Year*(SECS_PER_DAY * 365);
  for (i = 0; i < tm.Year; i++) {
    if (LEAP_YEAR(i)) {
      seconds +=  SECS_PER_DAY;   // add extra days for leap years
  // add days for this year, months start from 1
  for (i = 1; i < tm.Month; i++) {
    if ( (i == 2) && LEAP_YEAR(tm.Year)) { 
      seconds += SECS_PER_DAY * 29;
    } else {
      seconds += SECS_PER_DAY * monthDays[i-1];  //monthDay array starts from 0
  seconds+= (tm.Day-1) * SECS_PER_DAY;
  seconds+= tm.Hour * SECS_PER_HOUR;
  seconds+= tm.Minute * SECS_PER_MIN;
  seconds+= tm.Second;
  return seconds; 
/* Low level system time functions  */

static time_t sysTime = 0;
static time_t prevMillis = 0;
static time_t nextSyncTime = 0;
static timeStatus_t Status = timeNotSet;

getExternalTime getTimePtr;  // pointer to external sync function
//setExternalTime setTimePtr; // not used in this version

#ifdef TIME_DRIFT_INFO   // define this to get drift data
time_t sysUnsyncedTime = 0; // the time sysTime unadjusted by sync  

time_t now(){
  while( millis() - prevMillis >= 1000){      
    prevMillis += 1000;	
    sysUnsyncedTime++; // this can be compared to the synced time to measure long term drift     
  if(nextSyncTime <= sysTime){
	if(getTimePtr != 0){
	  time_t t = getTimePtr();
      if( t != 0)
        Status = (Status == timeNotSet) ?  timeNotSet : timeNeedsSync;        
  return sysTime;

void setTime(time_t t){ 
 if(sysUnsyncedTime == 0) 
   sysUnsyncedTime = t;   // store the time of the first call to set a valid Time   

  sysTime = t;  
  nextSyncTime = t + syncInterval;
  Status = timeSet; 
  prevMillis = millis();  // restart counting from now (thanks to Korman for this fix)

void  setTime(int hr,int min,int sec,int dy, int mnth, int yr){
 // year can be given as full four digit year or two digts (2010 or 10 for 2010);  
 //it is converted to years since 1970
  if( yr > 99)
      yr = yr - 1970;
      yr += 30;  
  tm.Year = yr;
  tm.Month = mnth;
  tm.Day = dy;
  tm.Hour = hr;
  tm.Minute = min;
  tm.Second = sec;

void adjustTime(long adjustment){
  sysTime += adjustment;

timeStatus_t timeStatus(){ // indicates if time has been set and recently synchronized
  return Status;

void setSyncProvider( getExternalTime getTimeFunction){
  getTimePtr = getTimeFunction;  
  nextSyncTime = sysTime;
  now(); // this will sync the clock

void setSyncInterval(time_t interval){ // set the number of seconds between re-sync
  syncInterval = interval;