LoginSignup
1
1

More than 5 years have passed since last update.

esp8266 で ds3231を使う2

Last updated at Posted at 2016-11-23

概要

RTC(リアルタイムクロック)を使うために時刻を設定する。しなくてもいいけど。

パソコンの時間と同期

数種類あるDS3231のライブラリうちひとつをダウンロード。
https://github.com/jarzebski/Arduino-DS3231

スケッチ:Arduino-DS3231.ino

void setup()
{
  Serial.begin(115200);

  // Initialize DS3231
  Serial.println("Initialize DS3231");
  clock.begin();

  // Set sketch compiling time
  clock.setDateTime(__DATE__, __TIME__);
}

clock.setDateTime(DATE, TIME);
このコードでパソコンの日時をESP8266に書き込む。。。

コンパイル書き込みに時間がかかるので、30秒ぐらい実時間と遅れることが判明(T_T)

ntpを使って同期

下のサイトを参考にntpのスケッチを書き込み動作確認
http://qiita.com/exabugs/items/b1b7430d185b268a1abf

動くことが確認できたので2つのスケッチを組み合わせてntpをつかって同期した

#include <ESP8266WiFi.h>
#include <NTP.h>
#include <Wire.h>
#include <DS3231.h>

DS3231 clock;
RTCDateTime dt;

char s[20];
const char* format = "%04d-%02d-%02d %02d:%02d:%02d";

void setup() {
  Serial.begin(115200);

  Serial.println();

  // 自分のネットワークに合わせてください
  WiFi.begin("SSID", "P/W");

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");

  Serial.println("WiFi connected");
  ntp_begin(2390);

//ds3231
  Serial.println("Initialize DS3231");;
  clock.begin();

  time_t n = now();
  time_t t;
  t = localtime(n, 9);
  clock.setDateTime(year(t), month(t), day(t), hour(t), minute(t), second(t));

}

void display(){
  time_t n = now();
  time_t t;
  t = localtime(n, 9);
  sprintf(s, format, year(t), month(t), day(t), hour(t), minute(t), second(t));
  Serial.print("NTP   : ");
  Serial.println(s);
}

void loop() {

    display();
    dt = clock.getDateTime();
    sprintf(s, format, dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second);
    Serial.print("DS3231: ");
    Serial.println(s);

  delay(1000);
}

これで大体パソコンと1秒以内の誤差でRTCの時刻を設定できた。

次は、定期処理を行う予定。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1