Arduinoには時計機能が無いため、時計機能を持たせるには外部RTCモジュール等を使う。
RTCモジュールの一つであるDS3231搭載モジュールは時計を設定しておくとコイン電池でArudinoの電源オフ時も時計情報を保持し、好きな時に時計を読み出すことが出来るが、時計機能以外にも温度センサーや設定可能な方形波出力信号出力、指定日時に割り込みで起こしてくれる2つのアラーム機能、32KbitのEEPROMが付いているなど単に時計機能だけでなく便利なおまけ機能も搭載されている。
通信はI2C信号で行う。DS3231の時計機能アドレスがデフォルト0x68、AT24C32のEEPROMのデフォルトアドレスが0x57となっている。時計機能を使うだけであれば、Vcc/Gnd/SCL/SDAの4つを繋ぐだけ。(Arduino UNOの場合、SCL/SDAはA5/A4ピンでも同じ)
制御にはライブラリを使うのが便利である。基本的な時計機能を使うだけであれば
https://www.sparkyswidgets.com/portfolio-item/arduino-rtc-tutorial/
にあるコードをテキストに落とすか、
https://www.pjrc.com/teensy/td_libs_DS1307RTC.html
のDS1307用ライブラリも中身は同じである。アラーム機能や波形を使う場合は
https://github.com/simonkuang/DS3231
のライブラリがある。下記サイトもEEPROMのアドレス等について説明されていて参考になる。
http://blogs.yahoo.co.jp/dascomp21/archive/2014/12/22?m=lc&p=1
(2015/4/23 追記)
下記ライブラリも使い易くお勧めである。アラームの使い方についてはRTCモジュールを使った定期処理の記事にて説明。
https://github.com/JChristensen/DS3232RTC
以下は上記sparkyswidgetsからの引用で、RTCから時計を取得し気温と合わせてシリアル出力するコード。RTCからの時計取得は電源オン直後の一回でその後精度が低いArduinoの時計機能を使っているだけなので注意。
#include <ds3231rtc.h>
#include <Time.h>
#include <Wire.h>
#include <DS3231RTC.h> // A simple DS3231 Library meant for use with Time.h also implements temp readings
void setup() {
Serial.begin(9600);
setSyncProvider(RTC.get); // the function to get the time from the RTC
if (timeStatus() != timeSet)
Serial.println("Unable to sync with the RTC");
else
Serial.println("RTC has set the system time");
}
void loop()
{
digitalClockDisplay();
delay(1000);
}
void digitalClockDisplay() {
// digital clock display of the time
Serial.print(hour());
printDigits(minute());
printDigits(second());
Serial.print(" ");
Serial.print(day());
Serial.print(" ");
Serial.print(month());
Serial.print(" ");
Serial.print(year());
Serial.print(" ");
Serial.print(RTC.getTemp()); //These last few lines are the only other change to the the Time.h example!
Serial.print((char)223);
Serial.print('C');
Serial.println();
}
void printDigits(int digits) {
// utility function for digital clock display: prints preceding colon and leading 0
Serial.print(":");
if (digits < 10)
Serial.print('0');
Serial.print(digits);
}




![[GPG] Arduino用RTCモジュール DS3231 / AT24C32](https://images-na.ssl-images-amazon.com/images/I/51qACLYPYEL._SL160_.jpg)






[…] ArduinoでRTCモジュールを使う https://programresource.net/2015/04/05/2519.html […]