본문 바로가기

ESP32

ESP32 실시간 클록 모듈(DS1302) RTC 모듈

반응형

ESP32 실시간 클록 모듈(DS1302) RTC 모듈 

 

이 레슨에서는 ESP32 개발 보드로 실시간 시계(RTC) 모듈을 설정하고 사용하는 방법을 배웁니다. DS1302 RTC 모듈을 통합하고, 그 기능을 이해하고, 현재 날짜와 시간을 표시하도록 ESP32를 프로그래밍하는 방법을 다룹니다. 또한 RTC가 날짜와 시간 설정을 잃어버린 상황을 처리하고 스케치의 컴파일 시간으로 자동으로 설정하는 방법도 배웁니다. 이 프로젝트는 마이크로컨트롤러 프로젝트에서 시간 관련 기능에 대한 이해도를 높이고자 하는 분들에게 이상적입니다. 

 

다른 모듈도 참고하세요. DS3231 RTC 모듈입니다. 사용법은 동일합니다.

 

이미지와 사용 예 https://esp32io.com/tutorials/esp32-rtc

 

위 모듈을 사용할 때 연결도를 참고하세요.

 

예제 코드 참고는 https://esp32io.com/tutorials/esp32-rtc

 

 

회로 연결

 

 

 

라이브러리를 설치하려면 아두이노 라이브러리 관리자를 사용하여 "Rtc by Makuna"를 검색하여 설치합니다. 

 

ESP32 전체 코드는 아래와 같습니다. 코드 설명은 아래에 이어집니다.

 

/*
  This code initializes and sets up the RTC DS1302 module and prints the current date and 
  time on the serial monitor. It also checks if the RTC is running and has a valid date and time. 
  If not, it sets the RTC to the compile time.
  Due to the time required for compilation and upload, there may be a time difference.

  Board: ESP32 Development Board
  Component: Real Time Clock Module  (DS1302)
  Library: https://github.com/Makuna/Rtc (Rtc by Makuna)
*/

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

const int IO = 27;    // DAT
const int SCLK = 14;  // CLK
const int CE = 26;    // RST

ThreeWire myWire(IO, SCLK, CE);
RtcDS1302<ThreeWire> Rtc(myWire);

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

  Serial.print("compiled: ");
  Serial.print(__DATE__);
  Serial.println(__TIME__);

  Rtc.Begin();

  RtcDateTime compiled = RtcDateTime(__DATE__, __TIME__);
  printDateTime(compiled);
  Serial.println();

  if (!Rtc.IsDateTimeValid()) {
    // Common Causes:
    //    1) first time you ran and the device wasn't running yet
    //    2) the battery on the device is low or even missing

    Serial.println("RTC lost confidence in the DateTime!");
    Rtc.SetDateTime(compiled);
  }

  if (Rtc.GetIsWriteProtected()) {
    Serial.println("RTC was write protected, enabling writing now");
    Rtc.SetIsWriteProtected(false);
  }

  if (!Rtc.GetIsRunning()) {
    Serial.println("RTC was not actively running, starting now");
    Rtc.SetIsRunning(true);
  }

  RtcDateTime now = Rtc.GetDateTime();
  if (now < compiled) {
    Serial.println("RTC is older than compile time!  (Updating DateTime)");
    Rtc.SetDateTime(compiled);
  } else if (now > compiled) {
    Serial.println("RTC is newer than compile time. (this is expected)");
  } else if (now == compiled) {
    Serial.println("RTC is the same as compile time! (not expected but all is fine)");
  }
}

void loop() {
  RtcDateTime now = Rtc.GetDateTime();

  printDateTime(now);
  Serial.println();

  if (!now.IsValid()) {
    // Common Causes:
    //    1) the battery on the device is low or even missing and the power line was disconnected
    Serial.println("RTC lost confidence in the DateTime!");
  }

  delay(1000);  // five seconds
}

#define countof(a) (sizeof(a) / sizeof(a[0]))

void printDateTime(const RtcDateTime& dt) {
  char datestring[20];

  snprintf_P(datestring,
             countof(datestring),
             PSTR("%02u/%02u/%04u %02u:%02u:%02u"),
             dt.Month(),
             dt.Day(),
             dt.Year(),
             dt.Hour(),
             dt.Minute(),
             dt.Second());
  Serial.print(datestring);
}

 

코드 분석입니다.

 

1. 초기화 및 라이브러리 포함 참고

 

라이브러리를 설치하려면 Arduino Library Manager를 사용하고 "Rtc by Makuna"를 검색하여 설치합니다.

 

여기에는 DS1302 RTC 모듈에 필요한 라이브러리가 포함되어 있습니다.

 

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

 

2. 핀 정의 및 RTC 인스턴스 생성

 

통신용 핀이 정의되고 RTC 인스턴스가 생성됩니다.

 

const int IO = 27;    // DAT
const int SCLK = 14;  // CLK
const int CE = 26;    // RST

ThreeWire myWire(IO, SCLK, CE));
RtcDS1302<ThreeWire> Rtc(myWire);

 

3. setup() 함수

 

이 함수는 직렬 통신을 초기화하고 RTC 모듈을 설정합니다. RTC가 올바르게 실행되는지 확인하기 위해 다양한 검사를 수행합니다.

 

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

  Serial.print("compiled: ");
  Serial.print(__DATE__);
  Serial.println(__TIME__);

  Rtc.Begin();

  RtcDateTime compiled = RtcDateTime(__DATE__, __TIME__);
  printDateTime(compiled);
  Serial.println();

  if (!Rtc.IsDateTimeValid()) {
    // Common Causes:
    //    1) first time you ran and the device wasn't running yet
    //    2) the battery on the device is low or even missing

    Serial.println("RTC lost confidence in the DateTime!");
    Rtc.SetDateTime(compiled);
  }

  if (Rtc.GetIsWriteProtected()) {
    Serial.println("RTC was write protected, enabling writing now");
    Rtc.SetIsWriteProtected(false);
  }

  if (!Rtc.GetIsRunning()) {
    Serial.println("RTC was not actively running, starting now");
    Rtc.SetIsRunning(true);
  }

  RtcDateTime now = Rtc.GetDateTime();
  if (now < compiled) {
    Serial.println("RTC is older than compile time!  (Updating DateTime)");
    Rtc.SetDateTime(compiled);
  } else if (now > compiled) {
    Serial.println("RTC is newer than compile time. (this is expected)");
  } else if (now == compiled) {
    Serial.println("RTC is the same as compile time! (not expected but all is fine)");
  }
}

 

 

4. loop() 함수

 

이 함수는 RTC에서 현재 날짜와 시간을 주기적으로 가져와 직렬 모니터에 인쇄합니다. 또한 RTC가 여전히 유효한 날짜와 시간을 유지하고 있는지 확인합니다.

 

void loop() {
  RtcDateTime now = Rtc.GetDateTime();

  printDateTime(now);
  Serial.println();

  if (!now.IsValid()) {
    // Common Causes:
    //    1) the battery on the device is low or even missing and the power line was disconnected
    Serial.println("RTC lost confidence in the DateTime!");
  }

  delay(5000);  // five seconds
}

 

5. 날짜 및 시간 인쇄 함수

 

RtcDateTime 객체를 가져와서 포맷된 날짜와 시간을 직렬 모니터에 인쇄하는 도우미 함수입니다.

 

void printDateTime(const RtcDateTime& dt) {
  char datestring[20];

  snprintf_P(datestring,
             countof(datestring),
             PSTR("%02u/%02u/%04u %02u:%02u:%02u"),
             dt.Month(),
             dt.Day(),
             dt.Year(),
             dt.Hour(),
             dt.Minute(),
             dt.Second());
  Serial.print(datestring);
}

 

 

위 참고자료는 ESP 교육 자료를 강의하는 SunFounder 자료임을 알려드리고, 이 링크를 따라가면 원본 문서를 보실 수 있습니다. 배움을 멈추지 마세요.

 

참고문서: DS3231을 사용한 ESP32 ESP-IDF RTC 실시간 클록 

 

 

반응형

캐어랩 고객 지원

취업, 창업의 막막함, 외주 관리, 제품 부재!

당신의 고민은 무엇입니까? 현실과 동떨어진 교육, 실패만 반복하는 외주 계약, 아이디어는 있지만 구현할 기술이 없는 막막함.

우리는 알고 있습니다. 문제의 원인은 '명확한 학습, 실전 경험과 신뢰할 수 있는 기술력의 부재'에서 시작됩니다.

이제 고민을 멈추고, 캐어랩을 만나세요!

코딩(펌웨어), 전자부품과 디지털 회로설계, PCB 설계 제작, 고객(시장/수출) 발굴과 마케팅 전략으로 당신을 지원합니다.

제품 설계의 고수는 성공이 만든 게 아니라 실패가 만듭니다. 아이디어를 양산 가능한 제품으로!

귀사의 제품을 만드세요. 교육과 개발 실적으로 신뢰할 수 있는 파트너를 확보하세요.

지난 30년 여정, 캐어랩이 얻은 모든 것을 함께 나누고 싶습니다.

카카오 채널 추가하기

카톡 채팅방에서 무엇이든 물어보세요

당신의 성공을 위해 캐어랩과 함께 하세요.

캐어랩 온라인 채널 바로가기

캐어랩