Arduinoを使ってセンサーデータの蓄積を行う準備として、リアルタイムクロック(RTC)を使ってみた。Arduinoは時計を持っていないため現在時刻がわからない、そこでRTCを使用すれば現在時刻とともにセンサーデータの保存ができるだろうという算段。
材料
リアルタイムクロック(RTC):DS3231
Arduino pro mini 5V
回路
ソースコード
PCからシリアル通信で日時の設定と取得ができるようにしてみた。
以下はデータシートからの抜粋。

//RTC
#include <Wire.h>
#define RTC_addr 0x68
#define ASCII_ZERO 48
String str_cmd = "";
void setup() {
Serial.begin(38400);
Wire.begin();
}
void loop() {
//マスターから受信したら
if(myReadLine() > 0){
I2C_action();
}
}
int myReadLine(void){
int cnt_buf = 0;
str_cmd = "";
char ch;
//受信したら
if(Serial.available() > 0){
delay(100);
cnt_buf = Serial.available();
for (int iii = 0; iii < cnt_buf; iii++){
ch = Serial.read();
str_cmd.concat(ch);
}
}
return cnt_buf;
}
//アクション選択
void I2C_action(void){
if(str_cmd == "RTC"){
RTC_read();
}else if(str_cmd == "RTC_set"){
RTC_set();
}
}
//日時を取得
void RTC_read(void){
char* pchDate = "1990/01/01";
char* pchTime = "00:00:00";
byte sec = 0;
byte mini = 0;
byte hour = 0;
byte day = 0;
byte date = 0;
byte month = 0;
byte year = 0;
Wire.beginTransmission(RTC_addr);
Wire.write(0x00);
Wire.endTransmission();
Wire.requestFrom(RTC_addr, 7);
if(Wire.available() >= 7)
{
sec = Wire.read();
mini = Wire.read();
hour = Wire.read();
day = Wire.read();
date = Wire.read();
month = Wire.read();
year = Wire.read();
pchTime[0] = bitRead(hour,5)*2 + bitRead(hour,4) + ASCII_ZERO;
pchTime[1] = (hour & B00001111) + ASCII_ZERO;
pchTime[3] = (mini>>4) + ASCII_ZERO;
pchTime[4] = (mini & B00001111) + ASCII_ZERO;
pchTime[6] = (sec>>4) + ASCII_ZERO;
pchTime[7] = (sec & B00001111) + ASCII_ZERO;
pchDate[0] = '2';
pchDate[1] = '0';
pchDate[2] = (year>>4) + ASCII_ZERO;
pchDate[3] = (year & B00001111) + ASCII_ZERO;
pchDate[5] = bitRead(month,4) + ASCII_ZERO;
pchDate[6] = (month & B00001111) + ASCII_ZERO;
pchDate[8] = (date>>4) + ASCII_ZERO;
pchDate[9] = (date & B00001111) + ASCII_ZERO;
Serial.print(pchDate);
Serial.print(",");
Serial.println(pchTime);
}
}
//日時を設定
void RTC_set(void){
//例)2015/5/5 23:21:00
byte sec = 0;
byte mini = B00100001;
byte hour = B00100011;
byte day = 3;
byte date = 5;
byte month = B10000101;
byte year = B00010101;
delay(100);
Wire.beginTransmission(RTC_addr);
Wire.write(0x00);
Wire.write(sec);
Wire.write(mini);
Wire.write(hour);
Wire.write(day);
Wire.write(date);
Wire.write(month);
Wire.write(year);
Wire.endTransmission();
delay(50);
Serial.println("RTC_set");
}






