Skip to content

Instantly share code, notes, and snippets.

@sashimizakana
Last active August 29, 2015 14:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sashimizakana/8992da928edb24ea215e to your computer and use it in GitHub Desktop.
Save sashimizakana/8992da928edb24ea215e to your computer and use it in GitHub Desktop.
Example of DS1307RTC Read&Write
var five = new require('johnny-five');
var RTC = 0x68;
var board = new five.Board();
board.on("ready", function() {
board.io.sendI2CConfig(0);
setTime();
setInterval(getTime,1000);
});
function fromBcd(num){
return parseInt((num >> 4 & 0xf).toString() + (num & 0xf).toString());
}
function toBcd(num){
return parseInt(num / 10) << 4 | parseInt(num % 10);
}
function pad(num){
return ("0" + num).slice(-2);
}
function getTime(){
//読み込みを始めるアドレスを書き込む
board.io.sendI2CWriteRequest(RTC,[0x00]);
board.io.sendI2CReadRequest(RTC,8,function(d){
var year = 2000 + fromBcd(d[6]);
var month = fromBcd(d[5]);
var date = fromBcd(d[4]);
var weekday = fromBcd(d[3]);//日曜日(1) - 土曜日(7)
var hours = fromBcd(d[2]);
var minutes = pad(fromBcd(d[1]));
var seconds = pad(fromBcd(d[0]));
console.log(year + "/" + month + "/" + date + " " + hours + ":" + minutes + ":" + seconds);
});
}
function setTime(){
var d = new Date();
/*
書き込むデータを配列で用意する
書き込み開始アドレス、秒、分、時、曜日、日、月、年の順番
曜日は1が日曜日なので+1
月は1が1月なので+1
年は二桁なので-100
*/
var dates = [
0x00
,toBcd(d.getSeconds())
,toBcd(d.getMinutes())
,toBcd(d.getHours())
,toBcd(d.getDay() + 1)
,toBcd(d.getDate())
,toBcd(d.getMonth() + 1)
,toBcd(d.getYear() - 100)
];
board.io.sendI2CWriteRequest(RTC,dates);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment