未分類

arduino ds1302

接線

D5 <–> CLK
D6 <–> DAT
D7 <–> RST
3V <–> VCC
G <–> GND

程式碼

#include <ThreeWire.h>
#include <RtcDS1302.h>

// DS1302 VCC --> 3.3v - 5v
ThreeWire myWire(D6, D5, D7); // DAT, CLK, RST
RtcDS1302<ThreeWire> Rtc(myWire);

void setup() {
  Serial.begin(115200);
  Rtc.Begin();
  /*
  //如果程式編譯當時的電腦時間與DS1302不同,就更改DS1302的時間
  if (Rtc.GetDateTime() != RtcDateTime(__DATE__, __TIME__))
  {
    Serial.println("RTC is older than compile time!  (Updating DateTime)");
    Rtc.SetDateTime(RtcDateTime(__DATE__, __TIME__));
  }
  */
}

void loop() {
    RtcDateTime now = Rtc.GetDateTime();
    printDateTime(now);
    Serial.println();
    if (!now.IsValid())
    {
        Serial.println("RTC lost confidence in the DateTime!");
    }
    delay(1000); // ten seconds
}

#define countof(a) (sizeof(a) / sizeof(a[0]))
void printDateTime(const RtcDateTime& dt)
{
  char datestring[20];
  snprintf_P(datestring, 
    countof(datestring),
    PSTR("%04u/%02u/%02u %02u:%02u:%02u"),
    dt.Year(),
    dt.Month(),
    dt.Day(),
    dt.Hour(),
    dt.Minute(),
    dt.Second()
  );
  Serial.print(datestring);
}

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。