본문 바로가기

아두이노우노 R4

아두이노 우노 R4 WiFI RTC 제어 꿀팁

반응형

 

아두이노 우노 R4 RTC 제어 꿀팁

 

아두이노 UNO R4 WiFi 실시간 시계

Arduino UNO R4 WiFi Real-Time Clock  

 

UNO R4 WiFi에서 실시간 시계(RTC)에 액세스하는 방법을 알아보세요.

 

 

시간은 흐르지도 않고, 영원한 것도 아니다.

 

 

이 튜토리얼에서는 아두이노 UNO R4 WiFi 보드에서 실시간 클록(RTC)에 액세스하는 방법을 배웁니다. RTC는 UNO R4 WiFi의 마이크로컨트롤러(RA4M1)에 내장되어 있습니다.

 

목표

이 프로젝트의 목표는 다음과 같습니다:

 

  • RTC의 시작 날짜 설정
  • 달력 형식의 RTC에서 날짜/시간에 액세스합니다.
  • 유닉스 형식으로 시간에 액세스합니다.

 

필요한 하드웨어 및 소프트웨어

 

  • 아두이노 IDE(온라인 또는 오프라인)
  • 아두이노 UNO R4 WiFi
  • 아두이노 르네사스 코어

 

실시간 시계(RTC)

 

UNO R4 WiFi의 RTC는 Renesas 코어에 포함된 RTC 라이브러리를 사용하여 액세스할 수 있습니다. 이 라이브러리를 사용하면 시간을 설정하거나 가져올 수 있을 뿐만 아니라 알람을 사용하여 인터럽트를 트리거할 수 있습니다.

 

UNO R4 WiFi에는 기판 전원 공급이 차단된 경우에도 온보드 RTC를 계속 실행하는 데 사용되는 VRTC 핀이 있습니다. 이를 사용하려면 VRTC 핀에 1.6~3.6V 범위의 전압을 인가합니다.

 

이 페이지에 제공된 예제는 RTC를 사용하는 많은 실용적인 예제가 있으며, 이를 시작하는 데 도움이 될 것입니다.

 

시간 설정

 

  • RTCTime startTime(30, Month::JUNE, 2023, 13, 37, 00, 요일::WEDNESDAY, SaveLight::SAVING_TIME_ACTIVE)
  • RTC.setTime(startTime)

 

RTC의 시작 시간을 설정하려면 RTCTime 객체를 생성하면 됩니다. 여기서 일, 월, 연, 시, 분, 초를 지정하고 요일과 일광 절약 모드를 지정할 수 있습니다.

 

그런 다음 시간을 설정하려면 setTime() 메서드를 사용합니다. 예제 코드가 아래에 있어요.

 

#include "RTC.h"

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

  RTC.begin();
  
  RTCTime startTime(30, Month::JUNE, 2023, 13, 37, 00, DayOfWeek::WEDNESDAY, SaveLight::SAVING_TIME_ACTIVE);

  RTC.setTime(startTime);
}

void loop(){
}

 

시간 가져오기

 

  • RTC.getTime(currentTime)

 

시간을 검색하려면 RTCTime 객체를 생성하고 getTime() 메서드를 사용하여 현재 시간을 검색해야 합니다.

 

이 예제에서는 시간을 설정 및 가져와서 currentTime이라는 RTCTime 객체에 저장합니다.

 

#include "RTC.h"

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

  RTC.begin();
  
  RTCTime startTime(30, Month::JUNE, 2023, 13, 37, 00, DayOfWeek::WEDNESDAY, SaveLight::SAVING_TIME_ACTIVE);

  RTC.setTime(startTime);
}

void loop(){
RTCTime currentTime;

// Get current time from RTC
RTC.getTime(currentTime);
}

 

 

날짜 및 시간 인쇄

 

위의 예제는 시간을 설정하고 가져와 객체에 저장하는 방법을 보여줍니다. 이 데이터는 일련의 메서드를 통해 검색할 수 있습니다:

 

  • getDayOfMonth()
  • getMonth()
  • getYear()
  • getHour()
  • getMinutes()
  • getSeconds()

 

아래 예제는 currentTime 객체에서 날짜와 시간을 출력합니다.

 

#include "RTC.h"

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

  RTC.begin();
  
  RTCTime startTime(30, Month::JUNE, 2023, 13, 37, 00, DayOfWeek::WEDNESDAY, SaveLight::SAVING_TIME_ACTIVE);

  RTC.setTime(startTime);
}

void loop() {
  RTCTime currentTime;

  // Get current time from RTC
  RTC.getTime(currentTime);

  // Print out date (DD/MM//YYYY)
  Serial.print(currentTime.getDayOfMonth());
  Serial.print("/");
  Serial.print(Month2int(currentTime.getMonth()));
  Serial.print("/");
  Serial.print(currentTime.getYear());
  Serial.print(" - ");

  // Print time (HH/MM/SS)
  Serial.print(currentTime.getHour());
  Serial.print(":");
  Serial.print(currentTime.getMinutes());
  Serial.print(":");
  Serial.println(currentTime.getSeconds());

  delay(1000);
}

 

유닉스

 

  • currentTime.getUnixTime()

 

유닉스 타임스탬프를 검색하려면 getUnixTime() 메서드를 사용합니다.

 

#include "RTC.h"

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

  RTC.begin();
  
  RTCTime startTime(30, Month::JUNE, 2023, 13, 37, 00, DayOfWeek::WEDNESDAY, SaveLight::SAVING_TIME_ACTIVE);

  RTC.setTime(startTime);
}

void loop() {
  RTCTime currentTime;

  // Get current time from RTC
  RTC.getTime(currentTime);
  
  //Unix timestamp
  Serial.print("Unix timestamp: ");
  Serial.println(currentTime.getUnixTime());

  delay(1000);
}

 

 

주기적 인터럽트

 

주기적 인터럽트를 사용하면 반복 콜백을 설정할 수 있습니다.

 

이를 사용하려면 setPeriodicCallback() 메서드를 사용하여 주기적 콜백을 초기화해야 합니다:

 

  • RTC.setPeriodicCallback(periodic_cbk, Period::ONCE_EVERY_2_SEC)

 

또한 호출할 함수를 생성해야 합니다:

 

  • void periodicCallback() { 실행할 코드 }

 

IRQ는 실행 시간이 매우 빠르다는 점에 유의하세요. 많은 코드를 배치하는 것은 좋은 방법이 아니므로 아래 예제에서는 단일 플래그인 irqFlag만 전환합니다.

 

아래 예시는 2초마다 불빛을 깜빡입니다:

 

#include "RTC.h"

volatile bool irqFlag = false;
volatile bool ledState = false;

const int led = LED_BUILTIN;

void setup() {
  pinMode(led, OUTPUT);

  Serial.begin(9600);

  // Initialize the RTC
  RTC.begin();

  // RTC.setTime() must be called for RTC.setPeriodicCallback to work, but it doesn't matter
  // what date and time it's set to
  RTCTime mytime(30, Month::JUNE, 2023, 13, 37, 00, DayOfWeek::WEDNESDAY, SaveLight::SAVING_TIME_ACTIVE);
  RTC.setTime(mytime);

  if (!RTC.setPeriodicCallback(periodicCallback, Period::ONCE_EVERY_2_SEC)) {
    Serial.println("ERROR: periodic callback not set");
  }
}

void loop(){
  if(irqFlag){
    Serial.println("Timed CallBack");
    ledState = !ledState;
    digitalWrite(LED_BUILTIN, ledState);
    irqFlag = false;
  }
}

void periodicCallback()
{
  irqFlag = true;
}

 

주기는 다음 열거형을 사용하여 지정할 수 있습니다:

 

  • ONCE_EVERY_2_SEC
  • ONCE_EVERY_1_SEC
  • N2_TIMES_EVER_SEC
  • N4_TIMES_EVER_SEC
  • N8_TIMES_EVER_SEC
  • N16_TIMES_EVER_SEC
  • N32_TIMES_EVER_SEC
  • N64_TIMES_EVER_SEC
  • N128_TIMES_EVER_SEC
  • N256_TIMES_EVER_SEC

알람 콜백

 

  • RTC.setAlarmCallback(alarm_cbk, alarmtime, am)
#include "RTC.h"

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

  RTC.begin();

  RTCTime alarmtime;
  alarmtime.setSecond(35);

  AlarmMatch am;
  am.addMatchSecond();

  if (!RTC.setAlarmCallback(alarm_cbk, alarmtime, am)) {
    Serial.println("ERROR: alarm callback not set");
  }
}

void alarm_cbk() {
  Serial.println("ALARM INTERRUPT");
}

 

네트워크 시간 프로토콜(NTP)

 

현재 시간을 검색하고 저장하기 위해 NTP 서버인 pool.ntp.org에 요청할 수 있습니다. 그러면 UNIX 타임스탬프가 검색되어 RTC 객체에 저장됩니다.

 

깃허브의 코드 소스

 

/**
 * RTC_NTPSync
 * 
 * This example shows how to set the RTC (Real Time Clock) on the Portenta C33 / UNO R4 WiFi
 * to the current date and time retrieved from an NTP server on the Internet (pool.ntp.org).
 * Then the current time from the RTC is printed to the Serial port.
 * 
 * Instructions:
 * 1. Download the NTPClient library (https://github.com/arduino-libraries/NTPClient) through the Library Manager
 * 2. Change the WiFi credentials in the arduino_secrets.h file to match your WiFi network.
 * 3. Upload this sketch to Portenta C33 / UNO R4 WiFi.
 * 4. Open the Serial Monitor.
 * 
 * Initial author: Sebastian Romero @sebromero
 * 
 * Find the full UNO R4 WiFi RTC documentation here:
 * https://docs.arduino.cc/tutorials/uno-r4-wifi/rtc
 */

// Include the RTC library
#include "RTC.h"

//Include the NTP library
#include <NTPClient.h>

#if defined(ARDUINO_PORTENTA_C33)
#include <WiFiC3.h>
#elif defined(ARDUINO_UNOWIFIR4)
#include <WiFiS3.h>
#endif

#include <WiFiUdp.h>
#include "arduino_secrets.h" 

///////please enter your sensitive data in the Secret tab/arduino_secrets.h
char ssid[] = SECRET_SSID;        // your network SSID (name)
char pass[] = SECRET_PASS;    // your network password (use for WPA, or use as key for WEP)

int wifiStatus = WL_IDLE_STATUS;
WiFiUDP Udp; // A UDP instance to let us send and receive packets over UDP
NTPClient timeClient(Udp);

void printWifiStatus() {
  // print the SSID of the network you're attached to:
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print your board's IP address:
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);

  // print the received signal strength:
  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
}

void connectToWiFi(){
  // check for the WiFi module:
  if (WiFi.status() == WL_NO_MODULE) {
    Serial.println("Communication with WiFi module failed!");
    // don't continue
    while (true);
  }

  String fv = WiFi.firmwareVersion();
  if (fv < WIFI_FIRMWARE_LATEST_VERSION) {
    Serial.println("Please upgrade the firmware");
  }

  // attempt to connect to WiFi network:
  while (wifiStatus != WL_CONNECTED) {
    Serial.print("Attempting to connect to SSID: ");
    Serial.println(ssid);
    // Connect to WPA/WPA2 network. Change this line if using open or WEP network:
    wifiStatus = WiFi.begin(ssid, pass);

    // wait 10 seconds for connection:
    delay(10000);
  }

  Serial.println("Connected to WiFi");
  printWifiStatus();
}

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

  connectToWiFi();
  RTC.begin();
  Serial.println("\nStarting connection to server...");
  timeClient.begin();
  timeClient.update();

  // Get the current date and time from an NTP server and convert
  // it to UTC +2 by passing the time zone offset in hours.
  // You may change the time zone offset to your local one.
  auto timeZoneOffsetHours = 2;
  auto unixTime = timeClient.getEpochTime() + (timeZoneOffsetHours * 3600);
  Serial.print("Unix time = ");
  Serial.println(unixTime);
  RTCTime timeToSet = RTCTime(unixTime);
  RTC.setTime(timeToSet);

  // Retrieve the date and time from the RTC and print them
  RTCTime currentTime;
  RTC.getTime(currentTime); 
  Serial.println("The RTC was just set to: " + String(currentTime));
}

void loop(){}

 

 

또한 자격 증명을 저장하는 데 사용되는 arduino_secrets.h라는 새 탭을 만들어야 합니다. 이 파일에 다음을 추가해야 합니다:

 

#define SECRET_SSID "" //network name
#define SECRET_PASS "" //network password

 

요약

 

이 튜토리얼은 시작 시간 설정, 알람 설정, 달력 또는 유닉스 형식의 시간 가져오기 등 UNO R4 WiFi에서 RTC를 사용하는 방법을 보여줍니다.

 

이 보드에 설명 자료는 이곳을 참고하세요. 

 

 

반응형

캐어랩 고객 지원

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

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

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

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

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

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

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

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

카카오 채널 추가하기

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

귀사가 성공하기까지의 긴 고난의 시간을 캐어랩과 함께 하세요.

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

캐어랩