Modifications

Sauter à la navigation Sauter à la recherche
2 328 octets ajoutés ,  20 janvier 2013 à 19:32
Ligne 114 : Ligne 114 :  
== Lire l'heure ==
 
== Lire l'heure ==
   −
xxx
+
Now that the RTC is merrily ticking away, we'll want to query it for the time. Lets look at the sketch again to see how this is done
 +
 
 +
<nowiki>void loop () {
 +
    DateTime now = RTC.now();
 +
   
 +
    Serial.print(now.year(), DEC);
 +
    Serial.print('/');
 +
    Serial.print(now.month(), DEC);
 +
    Serial.print('/');
 +
    Serial.print(now.day(), DEC);
 +
    Serial.print(' ');
 +
    Serial.print(now.hour(), DEC);
 +
    Serial.print(':');
 +
    Serial.print(now.minute(), DEC);
 +
    Serial.print(':');
 +
    Serial.print(now.second(), DEC);
 +
    Serial.println();</nowiki>
 +
 
 +
There's pretty much only one way to get the time using the RTClib, which is to call '''now()''', a function that returns a DateTime object that describes the year, month, day, hour, minute and second when you called '''now()'''.
 +
 
 +
There are some RTC libraries that instead have you call something like '''RTC.year()''' and '''RTC.hour()''' to get the current year and hour. However, there's one problem where if you happen to ask for the minute right at '''3:14:59''' just before the next minute rolls over, and then the second right after the minute rolls over (so at '''3:15:00''') you'll see the time as '''3:14:00''' which is a minute off. If you did it the other way around you could get '''3:15:59''' - so one minute off in the other direction.
 +
 
 +
Because this is not an especially unlikely occurance - particularly if you're querying the time pretty often - we take a 'snapshot' of the time from the RTC all at once and then we can pull it apart into '''day()''' or '''second()''' as seen above. Its a tiny bit more effort but we think its worth it to avoid mistakes!
 +
 
 +
We can also get a 'timestamp' out of the DateTime object by calling '''get''' which counts the number of seconds (not counting leapseconds) since midnight, January 1st 2000
 +
 
 +
<nowiki>    Serial.print(" since 2000 = ");
 +
    Serial.print(now.get());
 +
    Serial.print("s = ");
 +
    Serial.print(now.get() / 86400L);
 +
    Serial.println("d");</nowiki>
 +
 
 +
Since there are 60*60*24 = 86400 seconds in a day, we can easily count days since then as well. This might be useful when you want to keep track of how much time has passed since the last query, making some math a lot easier (like checking if its been 5 minutes later, just see if '''get()''' has increased by 300, you dont have to worry about hour changes)
    
{{ADF-RTC-DS1307-TRAILER}}
 
{{ADF-RTC-DS1307-TRAILER}}
29 839

modifications

Menu de navigation