티스토리 뷰

SWDesk/Firmware

시각 정보 얻기

inhae 2021. 11. 27. 08:37
  • NTPClient를 이용하여 "pool.ntp.org"로부터 현재 시각 정보 가져오기
  • 가져온 시각 정보를 하드웨어 내부 RTC에 저장
  • 필요 라이브러리 : NTPClient.h, RTCZero.h
void CheckCurrentTimefromNTP(){
  // Ref. : https://blog.naver.com/PostView.nhn?blogId=appti&logNo=221499699209&from=search&redirect=Log&widgetTypeCall=true&directAccess=false
  // Ref. : https://m.blog.naver.com/myunyui/222082845393
  WiFiUDP wiFiUDP;
  NTPClient timeClient(wiFiUDP, "pool.ntp.org", 32400);
  timeClient.begin();
  delay(10);
  timeClient.update();
  time_t epochTime = timeClient.getEpochTime();
  String formattedTime = timeClient.getFormattedTime();
  SerialUSB.print("[Formatted Time] ");
  SerialUSB.println(formattedTime);
  //SerialUSB.print("[EpochTime] ");
  //SerialUSB.println(epochTime);

//  struct tm *ptm = gmtime((time_t *)&epochTime);
  struct tm *ptm = localtime((time_t *)&epochTime);

  long currentYear = ptm->tm_year+1900;
  int currentMonth = ptm->tm_mon+1;
  int monthDay = ptm->tm_mday;
  int currentHour = ptm->tm_hour;
  int currentMins = ptm->tm_min;
  int currentSecs = ptm->tm_sec;
//  int currentHour = timeClient.getHours();
//  int currentMins = timeClient.getMinutes();
//  int currentSecs = timeClient.getSeconds();

  BClock.begin();
  BClock.setDate(monthDay, currentMonth, currentYear);
  BClock.setTime(currentHour, currentMins, currentSecs);

  SerialUSB.print("[Current DataTime] ");
  SerialUSB.print(String(currentYear));
  SerialUSB.print('-');
  if(currentMonth < 10) SerialUSB.print('0');
  SerialUSB.print(currentMonth);
  SerialUSB.print('-');
  if(monthDay < 10) SerialUSB.print('0');
  SerialUSB.print(monthDay);
  SerialUSB.print(' ');
  if(currentHour<10) SerialUSB.print('0');
  SerialUSB.print(currentHour);
  SerialUSB.print(':');
  if(currentMins<10) SerialUSB.print('0');
  SerialUSB.print(currentMins);
  SerialUSB.print(':');
  if(currentSecs<10) SerialUSB.print('0');
  SerialUSB.println(currentSecs);  

  timeClient.end();
}

 

반응형

'SWDesk > Firmware' 카테고리의 다른 글

RTC로부터 시각 정보를 String으로 변환  (0) 2021.11.30
Nano 33 Multiple Peripheral  (0) 2021.11.28
[Nano 33 IoT] Switch between BLE and WiFi  (2) 2021.11.21
[Nano 33 IoT] Test33  (0) 2021.11.17
[Nano 33 IoT] Test32  (0) 2021.11.17