Вы находитесь на странице: 1из 12

16/04/2015 UsingtheRealTimeClock|AdafruitDataLoggerShield|AdafruitLearningSystem

SearchAdafruit
SHOP
BLOG
LEARN
FORUMS
VIDEOS
SIGNIN
CLOSEMENU

0Items
SignIn

SHOP
PRODUCTCATEGORIES
(SEEALL27)
ARDUINO(129)
RASPBERRYPI(303)
BEAGLEBONE(24)
NEOPIXELS(34)
WEARABLES(95)
YOUNGENGINEERS(84)
COSPLAY/COSTUMING(148)
PROTOTYPING(160)
HALLOWEEN(210)
KITS&PROJECTS(142)
LCDS&DISPLAYS(97)
BOARDS(167)
RESELLER&UNIVERSITYPACKS(2)
LEDS(220)
POWER(151)
CABLES(102)
TOOLS(116)
ROBOTICS&CNC(126)
ACCESSORIES(110)
COMPONENTS&PARTS(263)
SENSORS(159)
ELWIRE/TAPE/PANEL(82)
3DPRINTING(53)
BOOKS(83)
SOFTWARE(7)
WIRELESS(65)
GIFTCERTIFICATES(4)
NEWPRODUCTS
(SEEALL119)

ArduinoGEMMAMiniaturewearableelectronicplatform

AdafruitDotStarLEDStripAPA102WarmWhite30LED/m~3000K$19.95

AdafruitDotStarLEDStripAPA102CoolWhite30LED/m~6000K$19.95

https://learn.adafruit.com/adafruitdataloggershield/usingtherealtimeclock 1/12
16/04/2015 UsingtheRealTimeClock|AdafruitDataLoggerShield|AdafruitLearningSystem

AdafruitDotStarLEDStripAPA102WarmWhite60LED/m~3000K$29.95

AdafruitDotStarLEDStripAPA102CoolWhite60LED/m~6000K$29.95
FEATUREDPRODUCTS
(SEEALL37)

AdafruitUSBIsolator100mAIsolatedLow/FullSpeedUSB$34.95

AdafruitTB66121.2ADC/StepperMotorDriverBreakoutBoard$4.95

PiTFTPlus480x3203.5"TFT+TouchscreenforRaspberryPi$44.95

RaspberryPi2ModelBStarterPackIncludesaRaspberryPi2$99.95

TheArtofElectronics3rdEditionbyHorowitz&HillHARDCOVER$120.00
BLOG
POPULARCATEGORIES
(SEEALL165)
ART(3104)
3DPRINTING(3071)
RANDOM(2718)
RASPBERRYPI(2646)
ARDUINO(2088)
WEARABLES(2040)
SCIENCE(1205)
ROBOTICS(1152)
LEDSLCDS(1126)
EE(1107)
MAKERBUSINESS(1044)
ANNOUNCE(979)
COSTUMING(953)
https://learn.adafruit.com/adafruitdataloggershield/usingtherealtimeclock 2/12
16/04/2015 UsingtheRealTimeClock|AdafruitDataLoggerShield|AdafruitLearningSystem
EDUCATORS(900)
ASKANENGINEER(887)
COSPLAY(837)
COMMUNITY(781)
OPENSOURCEHARDWARE(780)
TUTORIALS(550)
EVENTS(508)
NEWPOSTS
(SEEALL)

April16,2015at10:00am3DHangoutSound&Wood

April16,2015at9:00am3DPrintedPortableTrellisSoundboard

April16,2015at8:00amDevilMaryCryRebellionSword
FEATUREDPOSTS
(SEEALL46)

April10,2015at10:46pmBREAKINGNEWS:DataProfessionalsacquiredby

March31,2015at3:49pmTheArtofElectronics3rdEditionbyHorowitz

March27,2015at10:37pm#ArduinoD15
LEARN
GUIDECATEGORIES
(SEEALL751)
COMPONENTS(35)
SENSORS(122)
HACKS(22)
MICROCOMPUTERS(10)
ADAFRUITPRODUCTS(203)
MAKERBUSINESS(20)
PROJECTS(89)
LEDS(128)
RASPBERRYPI(157)
BRAINCRAFTS(31)
LCDS&DISPLAYS(46)
ELWIRE/TAPE/PANEL(11)
TOOLS(28)
MICROCONTROLLERS(61)
LEARNARDUINO(38)
CUSTOMERPROJECTS(16)
BEAGLEBONE(35)
CIRCUITPLAYGROUND(7)
3DPRINTING(92)
TRINKET(57)
ROBOTICS(13)
COLLIN'SLAB(7)
COMMUNITYSUPPORT(18)
WEARABLES(120)
NEWGUIDES
(SEEALL64)

https://learn.adafruit.com/adafruitdataloggershield/usingtherealtimeclock 3/12
16/04/2015 UsingtheRealTimeClock|AdafruitDataLoggerShield|AdafruitLearningSystem

SHOTTRACKERTEARDOWN

CREATEANINFRAREDCONTROLLEDMOUSEWITHARDUINOMICRO,LEONARDO,ORYUN

USINGANEXTERNALDRIVEASARASPBERRYPIROOTFILESYSTEM

PORTABLETRELLISSOUNDBOARD
FEATUREDGUIDES
(SEEALL116)

PLUSHGAMECONTROLLER

SECRETKNOCKACTIVATEDDRAWERLOCK

ADAFRUITLEDSEQUINS

INTRODUCINGPROTRINKET
FORUMS
VIDEOS

ADAFRUITPRODUCTS

https://learn.adafruit.com/adafruitdataloggershield/usingtherealtimeclock 4/12
16/04/2015 UsingtheRealTimeClock|AdafruitDataLoggerShield|AdafruitLearningSystem

AdafruitDataLogger
Shield
Adafruit'sDataLoggerShield,now
preassembled!

Overview
InstallingtheHeaders
ShieldOverview
UsingtheRealTimeClock
UsingtheSDCard
FortheMegaand
Leonardo
LightandTemperature
Logger
BuildIt!
UseIt!
CodeWalkthrough
Downloads

SinglePage
DownloadPDF

Contributors

BillEarl
ladyada
Feedback?Corrections?

UsingtheRealTimeClock

BILLEARL

WhatisaRealTimeClock?
Whenloggingdata,itsoftenreallyreallyusefultohavetimestamps!Thatwayyoucantakedataoneminuteapart(bycheckingtheclock)ornotingatwhattimeof
daythedatawaslogged.

TheArduinodoeshaveabuiltintimekeepercalledmillis()andtheresalsotimersbuiltintothechipthatcankeeptrackoflongertimeperiodslikeminutesordays.
SowhywouldyouwanttohaveaseparateRTCchip?Well,thebiggestreasonisthatmillis()onlykeepstrackoftimesincetheArduinowaslastpoweredthat
meansthatwhenthepoweristurnedon,themillisecondtimerissetbackto0.TheArduinodoesntknowits'Tuesday'or'March8th'allitcantellis'Itsbeen14,000
millisecondssinceIwaslastturnedon'.

OKsowhatifyouwantedtosetthetimeontheArduino?You'dhavetoprograminthedateandtimeandyoucouldhaveitcountfromthatpointon.Butifitlost
power,you'dhavetoresetthetime.Muchlikeverycheapalarmclocks:everytimetheylosepowertheyblink12:00

WhilethissortofbasictimekeepingisOKforsomeprojects,adataloggerwillneedtohaveconsistanttimekeepingthatdoesntresetwhentheArduinobattery
diesorisreprogrammed.Thus,weincludeaseparateRTC!TheRTCchipisaspecializedchipthatjustkeepstrackoftime.Itcancountleapyearsandknows
howmanydaysareinamonth,butitdoesn'ttakecareofDaylightSavingsTime(becauseitchangesfromplacetoplace)

https://learn.adafruit.com/adafruitdataloggershield/usingtherealtimeclock 5/12
16/04/2015 UsingtheRealTimeClock|AdafruitDataLoggerShield|AdafruitLearningSystem

ThisimageshowsacomputermotherboardwithaRealTimeClockcalledtheDS1387.Theresalithiumbatteryintherewhichiswhyitssobig.

TheRTCwe'llbeusingistheDS1307.It'slowcost,easytosolder,andcanrunforyearsonaverysmallcoincell.

Aslongasithasacoincelltorunit,theDS1307willmerrilytickalongforalongtime,evenwhentheArduinolosespower,orisreprogrammed.
YouMUSThaveacoincellinstalledfortheRTCtowork,ifthereisnocoincell,itwillactstranglyandpossiblyhangtheArduinosoALWAYSmakeSURE
there'sabatteryinstalled,evenifitsadeadbattery.

TalkingtotheRTC
TheRTCisani2cdevice,whichmeansituses2wirestotocommunicate.Thesetwowiresareusedtosetthetimeandretreiveit.OntheArduino,thepinsare
'fixed'tobeAnalog4and5forthebuiltini2ccapability.Thisisabitannoyingsinceofcoursewewanttohaveupto6analoginputstoreaddataandnowwe've
losttwo.Thereisawaytouseotherpins...however,thehardwareisbydefaultsetupforAnalog4and5soletsstartwiththatandthenlaterwe'llshowhowto
modifytheshield!

FortheRTClibrary,we'llbeusingaforkofJeeLab'sexcellentRTClibrary.Pleasedownloaditnow.TheninstallitinyourArduinodirectoryinafoldercalled
RTClib

FirstRTCtest
Thefirstthingwe'lldemonstrateisatestsketchthatwillreadthetimefromtheRTConceasecond.We'llalsoshowwhathappensifyouremovethebatteryand
replaceitsincethatcausestheRTCtohalt.Sotostart,removethebatteryfromtheholderwhiletheArduinoisnotpoweredorpluggedintoUSB.Wait3seconds
andthenreplacethebattery.ThisresetstheRTCchip.Nowloadupthefollowingsketch(whichisalsofoundinExamples>RTClib>ds1307)anduploaditto
yourArduinowiththedataloggershieldon!

CopyCode
1. //DateandtimefunctionsusingaDS1307RTCconnectedviaI2CandWirelib
2.
3. #include<Wire.h>
4. #include"RTClib.h"
5.
6. RTC_DS1307RTC;
7.
8. voidsetup(){
9. Serial.begin(57600);
10. Wire.begin();
11. RTC.begin();

https://learn.adafruit.com/adafruitdataloggershield/usingtherealtimeclock 6/12
16/04/2015 UsingtheRealTimeClock|AdafruitDataLoggerShield|AdafruitLearningSystem
12.
13. if(!RTC.isrunning()){
14. Serial.println("RTCisNOTrunning!");
15. //followinglinesetstheRTCtothedate&timethissketchwascompiled
16. //uncommentit&uploadtosetthetime,dateandstartruntheRTC!
17. //RTC.adjust(DateTime(__DATE__,__TIME__));
18. }
19.
20. }
21.
22. voidloop(){
23. DateTimenow=RTC.now();
24.
25. Serial.print(now.year(),DEC);
26. Serial.print('/');
27. Serial.print(now.month(),DEC);
28. Serial.print('/');
29. Serial.print(now.day(),DEC);
30. Serial.print('');
31. Serial.print(now.hour(),DEC);
32. Serial.print(':');
33. Serial.print(now.minute(),DEC);
34. Serial.print(':');
35. Serial.print(now.second(),DEC);
36. Serial.println();
37.
38. Serial.print("since1970=");
39. Serial.print(now.unixtime());
40. Serial.print("s=");
41. Serial.print(now.unixtime()/86400L);
42. Serial.println("d");
43.
44. //calculateadatewhichis7daysand30secondsintothefuture
45. DateTimefuture(now.unixtime()+7*86400L+30);
46.
47. Serial.print("now+7d+30s:");
48. Serial.print(future.year(),DEC);
49. Serial.print('/');
50. Serial.print(future.month(),DEC);
51. Serial.print('/');
52. Serial.print(future.day(),DEC);
53. Serial.print('');
54. Serial.print(future.hour(),DEC);
55. Serial.print(':');
56. Serial.print(future.minute(),DEC);
57. Serial.print(':');
58. Serial.print(future.second(),DEC);
59. Serial.println();
60.
61. Serial.println();
62. delay(3000);
63. }

NowruntheSerialterminalandmakesurethebaudrateissetcorrectlyat57600

bpsyoushouldseethefollowing:

WhenevertheRTCchiplosesallpower(includingthebackupbattery)itwillreportthetimeas0:0:0anditwon'tcountseconds(itsstopped).Wheneveryousetthe
time,thiswillkickstarttheclockticking.Sobasicallytheupshothereisthatyoushouldnevereverremovethebatteryonceyou'vesetthetime.Youshouldn'thave
toandthebatteryholderisverysnugsounlesstheboardiscrushed,thebatterywont'fallout'

Settingthetime
Withthesamesketchloaded,uncommentthelinethatstartswithRTC.adjustlikeso:

//followinglinesetstheRTCtothedate&timethissketchwascompiledRTC.adjust(DateTime(__DATE__,__TIME__))

Thislineisverycute,whatitdoesistaketheDateandTimeaccordingthecomputeryou'reusing(rightwhenyoucompilethecode)andusesthattoprogramthe
RTC.Ifyourcomputertimeisnotsetrightyoushouldfixthatfirst.ThenyoumustpresstheUploadbuttontocompileandthenimmediatelyupload.Ifyoucompile
andthenuploadlater,theclockwillbeoffbythatamountoftime.

ThenopenuptheSerialmonitorwindowtoshowthatthetimehasbeenset

https://learn.adafruit.com/adafruitdataloggershield/usingtherealtimeclock 7/12
16/04/2015 UsingtheRealTimeClock|AdafruitDataLoggerShield|AdafruitLearningSystem

Fromnowon,youwonthavetoeversetthetimeagain:thebatterywilllast5ormoreyears

Readingthetime
NowthattheRTCismerrilytickingaway,we'llwanttoqueryitforthetime.Letslookatthesketchagaintoseehowthisisdone

CopyCode
1. voidloop(){
2. DateTimenow=RTC.now();
3.
4. Serial.print(now.year(),DEC);
5. Serial.print('/');
6. Serial.print(now.month(),DEC);
7. Serial.print('/');
8. Serial.print(now.day(),DEC);
9. Serial.print('');
10. Serial.print(now.hour(),DEC);
11. Serial.print(':');
12. Serial.print(now.minute(),DEC);
13. Serial.print(':');
14. Serial.print(now.second(),DEC);
15. Serial.println();

There'sprettymuchonlyonewaytogetthetimeusingtheRTClib,whichistocallnow(),afunctionthatreturnsaDateTimeobjectthatdescribestheyear,month,
day,hour,minuteandsecondwhenyoucallednow().

TherearesomeRTClibrariesthatinsteadhaveyoucallsomethinglikeRTC.year()andRTC.hour()togetthecurrentyearandhour.However,there'soneproblem
whereifyouhappentoaskfortheminuterightat3:14:59justbeforethenextminuterollsover,andthenthesecondrightaftertheminuterollsover(soat3:15:00)
you'llseethetimeas3:14:00whichisaminuteoff.Ifyoudidittheotherwayaroundyoucouldget3:15:59sooneminuteoffintheotherdirection.

Becausethisisnotanespeciallyunlikelyoccuranceparticularlyifyou'requeryingthetimeprettyoftenwetakea'snapshot'ofthetimefromtheRTCallatonce
andthenwecanpullitapartintoday()orsecond()asseenabove.Itsatinybitmoreeffortbutwethinkitsworthittoavoidmistakes!

Wecanalsogeta'timestamp'outoftheDateTimeobjectbycallingunixtimewhichcountsthenumberofseconds(notcountingleapseconds)sincemidnight,
January1st1970

CopyCode
1. Serial.print("since2000=");
2. Serial.print(now.unixtime());
3. Serial.print("s=");
4. Serial.print(now.unixtime()/86400L);
5. Serial.println("d");

Sincethereare60*60*24=86400secondsinaday,wecaneasilycountdayssincethenaswell.Thismightbeusefulwhenyouwanttokeeptrackofhowmuch
timehaspassedsincethelastquery,makingsomemathaloteasier(likecheckingifitsbeen5minuteslater,justseeifunixtime()hasincreasedby300,youdont
havetoworryabouthourchanges)

SHIELDOVERVIEWUSINGTHESDCARD
Lastupdatedon20150416at02.39.52PMPublishedon20130412at03.22.30PM

$19.95
AdafruitAssembledDataLoggingshieldforArduino
ADDTOCART

https://learn.adafruit.com/adafruitdataloggershield/usingtherealtimeclock 8/12
16/04/2015 UsingtheRealTimeClock|AdafruitDataLoggerShield|AdafruitLearningSystem

$1.95
ShieldstackingheadersforArduino(R3Compatible)
ADDTOCART

$24.95
ArduinoUnoR3(Atmega328assembled)
ADDTOCART

$37.50
Lightandtemperaturedataloggerpack
ADDTOCART

$1.50
TMP36AnalogTemperaturesensor
ADDTOCART

$0.95
Photocell(CdSphotoresistor)
ADDTOCART

https://learn.adafruit.com/adafruitdataloggershield/usingtherealtimeclock 9/12
16/04/2015 UsingtheRealTimeClock|AdafruitDataLoggerShield|AdafruitLearningSystem

$7.95
SD/MicroSDMemoryCard(4GBSDHC)
ADDTOCART

$5.00
6xAAbatteryholderwith5.5mm/2.1mmplug
ADDTOCART

$3.95
9Vbatteryholderwithswitch&5.5mm/2.1mmplug
ADDTOCART
ADDALLTOCART

RELATEDGUIDES
MICROCONTROLLERS

CloudThermometer

KitchenthermometerthatlogsdatatotheclouddirectlyoveraWiFinetwork!
UseanArduinoandCC3000tobuildakitchenthermometerthatlogstoAmazon'sDynamoDBservicesoitcanbeaccessedovertheweb,andpredictwhenfoodis
cooked.

TONYDICOLA

PROJECTS

https://learn.adafruit.com/adafruitdataloggershield/usingtherealtimeclock 10/12
16/04/2015 UsingtheRealTimeClock|AdafruitDataLoggerShield|AdafruitLearningSystem

WiFiWeatherStation

MakeaWiFiconnectedweatherstationusingArduino&theCC3000WiFichip!
TheAdafruit'sCC3000breakoutboardallowstoeasilyconnectyourArduinoprojectstoyourlocalWiFinetwork!Thisprojectdetailshowtobuildasimpleweather
stationthatrecordstemperature&humidityinyourhome,andhowtotransmitthedatatoaninterfaceonyourcomputerusingWiFi.

M.SCHWARTZ

MICROCONTROLLERS

HowtoFindHiddenCOMPorts

There,underarock!ItsagaggleofCOMports!
ThisminitutorialwillshowyouhowyoucanfindanduninstallallthoseextraCOMportsyoumayhaveregisteredfromyearsofmicrocontrollerhacking

LADYADA

LEARNARDUINO

ArduinoLesson9.SensingLight

LearnArduino,Lesson9.SensingLight
ThisisLesson8intheLearnArduinoAdafruitseries.Inthislesson,youwilllearnhowtomeasurelightintensityusinganAnalogInput.Youwillthenbuildon
lesson8andusetheleveloflighttocontrolthenumberofLEDstobelit.

SIMONMONK

OUTOFSTOCKNOTIFICATION

YOURNAME
YOUREMAIL
NOTIFYME

CONTACT
SUPPORT
DISTRIBUTORS
EDUCATORS
JOBS
FAQ
SHIPPING&RETURNS
TERMSOFSERVICE
PRIVACY&LEGAL
ABOUTUS

ENGINEEREDINNYCAdafruit
"Wearethemusicmakers,Andwearethedreamersofdreams"ArthurO'Shaughnessy

https://learn.adafruit.com/adafruitdataloggershield/usingtherealtimeclock 11/12
16/04/2015 UsingtheRealTimeClock|AdafruitDataLoggerShield|AdafruitLearningSystem

https://learn.adafruit.com/adafruitdataloggershield/usingtherealtimeclock 12/12

Вам также может понравиться