Does Arduino have any clock function? like say sec. min, Hour, date? wich one of the family does have any clock built? cheers all.
Look into using the Time library.
http://playground.arduino.cc/code/time
Also, for accuracy and power fail recovery, look at a RTC, ex: DS3231
.
I found the [u]Arduino Time Library[/u], but I've never used it. At first glance it looks like the standard C/C++ time functions.
But most people use a real time clock module, which contains battery (so you don't have to re-set the time after turning-off or loosing power) and it usually has a more accurate crystal.
For that, you have a choice:
Option #1: Make your own "clock functions". Here is sample code for this. (I did not test this code, so I'm not 100% sure it will run perfectly on the first try.)
// this part goes right at the beginning of your sketch, before setup
int ss=0, mi=0, hh=0, dd=0;
unsigned long lastSecond = 0UL;
// this part goes inside your loop
if ((micros() - lastSecond) >= 1000000UL) {
 // start a new second
 lastSecond += 1000000UL; Â
 // update count of seconds
 ss++;
 // do the "carries"
 if (ss >= 60) {
  // sixty seconds make one minute
  ss -= 60;
  mi++;
  if (mi >= 60) {
   // sixty minutes make one hour
   mi -= 60;
   hh++;
   if (hh >= 24) {
    // twenty-four hours make one day
    hh -= 60;
    dd++;
   }
  }
 }
}
Option #2: Get what's called an "external RTC". Google "DS1307" and "DS3231". The DS3231 has amazing accuracy.
Just so you know, there is nothing magical about the Time library. It is a form of my "Option #1", except that you are using code written by someone else to do it.
If you know how to do something once per second (like in Blink Without Delay), and you know how to use if
statements (like on this page), you can in a few minutes write something just as good as the Time library, and with the advantage that you know exactly how it is all put together. I consider this an excellent programming exercise for a beginner.
Okay, I fibbed. Writing your own clock (hours, minutes, and seconds) is very easy, but when you start on calendar stuff, it becomes a little trickier. The only reason that the calendar stuff is trickier is because not all months have the same number of days. But once you write your own function to give the number of days in each month (also an excellent programming exercise for a learner), the rest will be easy.
DVDdoug:
I found the [u]Arduino Time Library[/u], but I've never used it. At first glance it looks like the standard C/C++ time functions.But most people use a real time clock module, which contains battery (so you don't have to re-set the time after turning-off or loosing power) and it usually has a more accurate crystal.
The time library also has a synchronization capability that can be used to sync up with an RTC.
That way you use the time library calls to get/set the time and if you have an RTC, you can tell the Time library to use the RTC to initialize the time tracked by the Time library when the system boots as well as to periodically get the time from the RTC to ensure the time accuracy.
The value of the using the Time library is it has all the utility functions for extracting time/date elements that you may need and most importantly that it tracks time using a time_t so that calculating time difference between two times is trivial which is not the case if you are using human time of hours, mins, sec, month, day, year.
You can then add on the TimeAlarms library if you want to set alarms and then there is also another library to do Timezones and automatic daylight savings conversions as well if you need that.
--- bill
Delta_G:
There's absolutely no reason to keep separate variables for hours, minutes, seconds, etc. Just keep track of unix time, seconds since midnight Jan 1, 1970. Then whenever you need houre, minutes, seconds, etc. for display, you can just calculate them from that unix time. That's much simpler than trying to roll everything over at 59 and keep track of months and stuff in your counting code.
That has its own disadvantage: you end up with a lot of divisions and modulo operations. And the "human readable" time is likely to be used for more than just display: think of an alarm clock.
Perhaps a compromise approach is best: seconds, minutes, hours, and a running count of days. I have used this successfully in my own code.
EDIT PS. The Time library makes really short work of converting unix time to hours, minutes, seconds, month, day, etc.
That's if you're going to be using Unix time.
And with my daysInMonth function, even that is not so difficult. (Just be careful of off-by-one errors: months should begin on day 1, not day 0.)
int days_in_month (int y, int m) {
// Fourth, eleventh, ninth, and sixth,
// thirty days to each we fix.
if ((m==4)||(m==11)||(m==9)||(m==6)) return 30;
// Every other, thirty-one,
// except the second month alone,
if (m!=2) return 31;
// which hath twenty-eight, in fine,
// till leap-year give it twenty-nine.
if ((y%400)==0) return 29; // leap year
if ((y%100)==0) return 28; // not a leap year
if ((y%4)==0) return 29; // leap year
return 28; // not a leap year
}
There are basically two ways to track time.
One that is easiest for humans (hrs, mins, secs, mon, day, year) or one that is easiest for machines (using an epoch based time like a unix time_t)
Either can work.
If you are doing something really simple and are only going to display a time on a display and nothing else, then it may make sense to track time in human form especially if using an RTC since the RTC chip does all the needed date/time calculations and updates every second.
Once the RTC is set, you simply read the RTC, display the desired date/time fields.
But once you start to do more complex things like support timezones, daylight savings corrections, comparing date/times or want to use alarms based on date/times, using an epoch based time can make things much easier.
Comparing two date/times is trivial when using an epoch time and is ridiculously hard and sometimes impossible when using human date/times since you may not know the timezone if all you have is HH:MM:SS DAY/MON/YEAR. (in those cases the human has to enter the missing information)
Unless there was a desire to actually learn about time keeping and write some time keeping code or I2C routines to read a RTC clock. I'd recommend using the Time library even if there was a desire to simply display the date/time on a display.
The reason being is that the Time library code is already written and debugged including examples, and has support for using an RTC to set and synchronize the time(examples included show how to do this), and with additional libraries can be extended to support Alarms, Timezones, and automatic daylight savings corrections should any of those be wanted/needed.
--- bill
You can do a real simple time counter:
unsigned long currentMicros;
unsigned long previousMicros;
unsigned long elapsedTime;
byte hundredths;
byte tenths;
byte secondsOnes;
byte oldSecondsOnes;
byte secondsTens;
byte minutesOnes = 0;
byte minutesTens = 4;
byte hoursOnes = 1;
byte hoursTens = 1;
void setup(){
 Serial.begin(115200); // make serial monitor match
 currentMicros = micros();
 previousMicros = currentMicros;
 Serial.println ("Setup Done");
}
void loop(){
 currentMicros = micros();
 // how long's it been?
 elapsedTime = currentMicros - previousMicros;
 Serial.print ("Elapsed: "); Â
 Serial.println (elapsedTime);
 if ( elapsedTime >=10000UL){  // 0.01 second passed? Update the timers
  elapsedTime = 0;
  previousMicros  = previousMicros + 10000UL;
  hundredths = hundredths+1;
  if (hundredths == 10){
   hundredths = 0;
   tenths = tenths +1;
   if (tenths == 10){
    tenths = 0;
    secondsOnes = secondsOnes + 1;
    if (secondsOnes == 10){
     secondsOnes = 0;
     secondsTens = secondsTens +1;
     if (secondsTens == 6){Â
      secondsTens = 0;
      minutesOnes =  minutesOnes + 1;
      if (minutesOnes == 10){
       minutesOnes = 0;
       minutesTens = minutesTens +1;
       if (minutesTens == 6){
        minutesTens = 0;
        hoursOnes = hoursOnes +1;
        if (hoursOnes == 10){
         hoursOnes = 0;
         hoursTens = hoursTens =1;
         if (hoursOnes == 4 && hoursTens ==2){
          hoursOnes = 0;
          hoursTens = 0;
         }
        }
       } // minutesTens rollover check
      } // minutesOnes rollover check
     } // secondsTens rollover check
    } // secondsOnes rollover check
   } // tenths rollover check
  } // hundredths rollover check
 } // hundredths passing check
 if (oldSecondsOnes != secondsOnes){  // show the elapsed time
  oldSecondsOnes = secondsOnes;
  Serial.print ("Time: ");
  Serial.print (hoursTens);
  Serial.print(hoursOnes);
  Serial.print(":");
  Serial.print(minutesTens);
  Serial.print(minutesOnes);
  Serial.print(":");
  Serial.print(secondsTens);
  Serial.println(secondsOnes);
 } // end one second check
} // end loop
CrossRoads:
You can do a real simple time counter:
What about the date function that the OP asked for in the initial post.
Not so simple anymore.
--- bill
bperrybap:
The time library also has a synchronization capability that can be used to sync up with an RTC.
That way you use the time library calls to get/set the time and if you have an RTC, you can tell the Time library to use the RTC to initialize the time tracked by the Time library when the system boots as well as to periodically get the time from the RTC to ensure the time accuracy.
For that, don't you also need an RTC library in addition to the Time library?
The value of the using the Time library is it has all the utility functions for extracting time/date elements that you may need and most importantly that it tracks time using a time_t so that calculating time difference between two times is trivial which is not the case if you are using human time of hours, mins, sec, month, day, year.
If I need a time difference, I'll probably use a micros() timestamp or similar.
For longer intervals, yes, I probably would use something like:
long timeInterval(int h1, int m1, int s1, int h2, int m2, int s2) {
long diff = ((h2*3600L)+(m2*60L)+s2) - ((h1*3600L)+(m1*60L)+s1);
if (diff >= 0) return diff;
return (diff + 86400L);
}
You can then add on the TimeAlarms library if you want to set alarms
Depending on what you're trying to do, maybe much better to roll your own.
Example: Problem Adjusting Alarm time on Alarm Clock - Programming Questions - Arduino Forum
and then there is also another library to do Timezones and automatic daylight savings conversions as well if you need that.
I prefer to muck about with arithmetic.
You prefer to muck about with libraries.
Delta_G:
It's a clock. How much does it really need to be optimized for performance? I think we can spare a few microseconds to do a divide operation. And we only need those when we are doing a display. Writing to a display will obviously be much slower so the divide and modulo aren't going to be the choke points. And compare the expense of a divide once in a while for display to the constant comparisons and adjustments that have to be made every single second to keep 6 different variables updated constantly. The savings start to wither.
Ask Atmel. Their suggested code for implementing a real time clock in an AVR chip is exactly that: keeping each variable separately and doing comparisons.
This is clearly faster since 59 times out of 60 (or even 9 times out of 10 if you break the digits down) you do an increment of a single byte variable and one single byte comparison. One time out of 60 you have to increment a second byte and do a second comparison. Even without having to convert a long into seconds, minutes, hours, date, month, year and day, just the process of incrementing a 32-bit variable takes slightly longer. And 32-bit division/modulo arithmetic on an 8-bit AVR takes longer than "a few microseconds".
Sometimes it matters. Suppose you want the clock to run for a long time off of a small battery. That's hardly an atypical application and it's the one that Atmel addresses.
Delta_G:
As ridiculous as it seems to keep hours and minutes in separate variables, it is totally overshadowed by this. Why would I need to keep the tens place and ones place of my number in separate variables?
You don't need to, but it can make things easier for when you want to display a number or adjust each digit separately.
Actually, a "fun" way to do this sort of thing is explained here:
Jones on BCD arithmetic
At least some of his code could use improvement (the subtraction algorithm in particular), but I think it's kind of cool anyway.
Oh, and since we're talking about clocks:
unsigned long timeAdd (unsigned long x, unsigned long y) {
// no sanity checking of input
// format is hhmmssff with ff being decimal fractions of a second
// "out of range" results are e.g. A0000000 for 100 hours
unsigned long binsum = x + y;
unsigned long carry = ((binsum + 0x06A6A666) ^ x ^ y) & 0x11111110;
return (binsum + ((carry - (carry>>4)) & 0x06A6A666));
}
unsigned long timeSub (unsigned long x, unsigned long y) {
// no sanity checking of input
// format is hhmmssff with ff being decimal fractions of a second
// "negative" results are e.g. F9595999 for -0.01 second
unsigned long bindiff = x - y;
unsigned long borrow = (bindiff ^ x ^ y) & 0x11111110;
return (bindiff - ((borrow - (borrow>>4)) & 0x06A6A666) );
}
Test code here: p6Cn6M - Online C++0x Compiler & Debugging Tool - Ideone.com