Arduino UNO R4 WiFi Real-Time Clock
Learn how to access the real-time clock (RTC) on the UNO R4 WiFi.
In this tutorial you will learn how to access the real-time clock (RTC) on an Arduino UNO R4 WiFi board. The RTC is embedded in the UNO R4 WiFi's microcontroller (RA4M1).
Goals
The goals of this project are:
- Set a start date of the RTC
- Access the date / time from the RTC in calendar format.
- Access the time in Unix format.
Hardware & Software Needed
- Arduino IDE (online or offline)
- Arduino UNO R4 WiFi
- UNO R4 Board Package
Real-Time Clock (RTC)
The RTC on the UNO R4 WiFi can be accessed using the RTC library that is included in the UNO R4 Board Package. This library allows you to set/get the time as well as using alarms to trigger interrupts.
The UNO R4 WiFi features a VRTC pin, that is used to keep the onboard RTC running, even when the boards power supply is is cut off. In order to use this, apply a voltage in the range of 1.6 - 3.6 V to the VRTC pin.
There are many practical examples using an RTC, and the examples provided in this page will help you get started with it.
Set Time
RTCTime startTime(30, Month::JUNE, 2023, 13, 37, 00, DayOfWeek::WEDNESDAY, SaveLight::SAVING_TIME_ACTIVE)
RTC.setTime(startTime)
To set the starting time for the RTC, you can create an
RTCTime
object. Here you can specify the day, month, year, hour, minute, second, and specify day of week as well as daylight saving mode.Then to set the time, use the
setTime()
method.Example:
1#include "RTC.h"2
3void setup() {4 Serial.begin(9600);5
6 RTC.begin();7 8 RTCTime startTime(30, Month::JUNE, 2023, 13, 37, 00, DayOfWeek::WEDNESDAY, SaveLight::SAVING_TIME_ACTIVE);9
10 RTC.setTime(startTime);11}12
13void loop(){14}
Get Time
RTC.getTime(currentTime)
To retrieve the time, we need to create a
RTCTime
object, and use the getTime()
method to retrieve the current time.This example sets & gets the time and stores it in an
RTCTime
object called currentTime
.1#include "RTC.h"2
3void setup() {4 Serial.begin(9600);5
6 RTC.begin();7 8 RTCTime startTime(30, Month::JUNE, 2023, 13, 37, 00, DayOfWeek::WEDNESDAY, SaveLight::SAVING_TIME_ACTIVE);9
10 RTC.setTime(startTime);11}12
13void loop(){14RTCTime currentTime;15
16// Get current time from RTC17RTC.getTime(currentTime);18}
Print Date & Time
The above examples show how to set & get the time and store it in an object. This data can be retrieved by a series of methods:
getDayOfMonth()
getMonth()
getYear()
getHour()
getMinutes()
getSeconds()
The example below prints out the date and time from the
currentTime
object.1#include "RTC.h"2
3void setup() {4 Serial.begin(9600);5
6 RTC.begin();7 8 RTCTime startTime(30, Month::JUNE, 2023, 13, 37, 00, DayOfWeek::WEDNESDAY, SaveLight::SAVING_TIME_ACTIVE);9
10 RTC.setTime(startTime);11}12
13void loop() {14 RTCTime currentTime;15
16 // Get current time from RTC17 RTC.getTime(currentTime);18
19 // Print out date (DD/MM//YYYY)20 Serial.print(currentTime.getDayOfMonth());21 Serial.print("/");22 Serial.print(Month2int(currentTime.getMonth()));23 Serial.print("/");24 Serial.print(currentTime.getYear());25 Serial.print(" - ");26
27 // Print time (HH/MM/SS)28 Serial.print(currentTime.getHour());29 Serial.print(":");30 Serial.print(currentTime.getMinutes());31 Serial.print(":");32 Serial.println(currentTime.getSeconds());33
34 delay(1000);35}
Unix
currentTime.getUnixTime()
To retrieve the Unix timestamp, use the
getUnixTime()
method.1#include "RTC.h"2
3void setup() {4 Serial.begin(9600);5
6 RTC.begin();7 8 RTCTime startTime(30, Month::JUNE, 2023, 13, 37, 00, DayOfWeek::WEDNESDAY, SaveLight::SAVING_TIME_ACTIVE);9
10 RTC.setTime(startTime);11}12
13void loop() {14 RTCTime currentTime;15
16 // Get current time from RTC17 RTC.getTime(currentTime);18 19 //Unix timestamp20 Serial.print("Unix timestamp: ");21 Serial.println(currentTime.getUnixTime());22
23 delay(1000);24}
Periodic Interrupt
A periodic interrupt allows you to set a recurring callback.
To use this, you will need to initialize the periodic callback, using the
setPeriodicCallback()
method:RTC.setPeriodicCallback(periodic_cbk, Period::ONCE_EVERY_2_SEC)
You will also need to create a function that will be called:
void periodicCallback() { code to be executed }
Note the IRQ has a very fast execution time. Placing a lot of code is not a good practice, so in the example below we are only switching a single flag,
.irqFlag
The example below blinks a light every 2 seconds:
1#include "RTC.h"2
3volatile bool irqFlag = false;4volatile bool ledState = false;5
6const int led = LED_BUILTIN;7
8void setup() {9 pinMode(led, OUTPUT);10
11 Serial.begin(9600);12
13 // Initialize the RTC14 RTC.begin();15
16 // RTC.setTime() must be called for RTC.setPeriodicCallback to work, but it doesn't matter17 // what date and time it's set to18 RTCTime mytime(30, Month::JUNE, 2023, 13, 37, 00, DayOfWeek::WEDNESDAY, SaveLight::SAVING_TIME_ACTIVE);19 RTC.setTime(mytime);20
21 if (!RTC.setPeriodicCallback(periodicCallback, Period::ONCE_EVERY_2_SEC)) {22 Serial.println("ERROR: periodic callback not set");23 }24}25
26void loop(){27 if(irqFlag){28 Serial.println("Timed CallBack");29 ledState = !ledState;30 digitalWrite(LED_BUILTIN, ledState);31 irqFlag = false;32 }33}34
35void periodicCallback()36{37 irqFlag = true;38}
The period can be specified using the following enumerations:
ONCE_EVERY_2_SEC
ONCE_EVERY_1_SEC
N2_TIMES_EVERY_SEC
N4_TIMES_EVERY_SEC
N8_TIMES_EVERY_SEC
N16_TIMES_EVERY_SEC
N32_TIMES_EVERY_SEC
N64_TIMES_EVERY_SEC
N128_TIMES_EVERY_SEC
N256_TIMES_EVERY_SEC
Alarm Callback
RTC.setAlarmCallback(alarm_cbk, alarmtime, am)
1unsigned long previousMillis = 0;2const long interval = 1000;3bool ledState = false;4
5// Include the RTC library6#include "RTC.h"7
8void setup() {9 //initialize Serial Communication10 Serial.begin(9600);11
12 //define LED as output13 pinMode(LED_BUILTIN, OUTPUT);14
15 // Initialize the RTC16 RTC.begin();17
18 // RTC.setTime() must be called for RTC.setAlarmCallback to work, but it doesn't matter19 // what date and time it's set to in this example20 RTCTime initialTime(7, Month::JUNE, 2023, 13, 03, 00, DayOfWeek::WEDNESDAY, SaveLight::SAVING_TIME_ACTIVE);21 RTC.setTime(initialTime);22
23 // Trigger the alarm every time the seconds are zero24 RTCTime alarmTime;25 alarmTime.setSecond(0);26
27 // Make sure to only match on the seconds in this example - not on any other parts of the date/time28 AlarmMatch matchTime;29 matchTime.addMatchSecond();30
31 //sets the alarm callback32 RTC.setAlarmCallback(alarmCallback, alarmTime, matchTime);33}34
35void loop() {36
37 // in the loop, we continuously print the alarm's current state38 // this is for debugging only and has no effect on the alarm whatsoever39 unsigned long currentMillis = millis();40 if (currentMillis - previousMillis >= interval) {41 // save the last time you blinked the LED42 previousMillis = currentMillis;43 Serial.print("Alarm state: ");44 Serial.println(ledState);45 }46}47
48// this function activates every minute49// and changes the ledState boolean50void alarmCallback() {51 if (!ledState) {52 digitalWrite(LED_BUILTIN, HIGH);53 } else {54 digitalWrite(LED_BUILTIN, LOW);55 }56 ledState = !ledState;57}
Network Time Protocol (NTP)
To retrieve and store the current time, we can make a request to an NTP server,
pool.ntp.org
. This will retrieve the UNIX time stamp and store it in an RTC
object. 1/**2 * RTC_NTPSync3 * 4 * This example shows how to set the RTC (Real Time Clock) on the Portenta C33 / UNO R4 WiFi5 * to the current date and time retrieved from an NTP server on the Internet (pool.ntp.org).6 * Then the current time from the RTC is printed to the Serial port.7 * 8 * Instructions:9 * 1. Download the NTPClient library (https://github.com/arduino-libraries/NTPClient) through the Library Manager10 * 2. Change the WiFi credentials in the arduino_secrets.h file to match your WiFi network.11 * 3. Upload this sketch to Portenta C33 / UNO R4 WiFi.12 * 4. Open the Serial Monitor.13 * 14 * Initial author: Sebastian Romero @sebromero15 * 16 * Find the full UNO R4 WiFi RTC documentation here:17 * https://docs.arduino.cc/tutorials/uno-r4-wifi/rtc18 */19
20// Include the RTC library21#include "RTC.h"22
23//Include the NTP library24#include <NTPClient.h>25
26#if defined(ARDUINO_PORTENTA_C33)27#include <WiFiC3.h>28#elif defined(ARDUINO_UNOWIFIR4)29#include <WiFiS3.h>30#endif31
32#include <WiFiUdp.h>33#include "arduino_secrets.h" 34
35///////please enter your sensitive data in the Secret tab/arduino_secrets.h36char ssid[] = SECRET_SSID; // your network SSID (name)37char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP)38
39int wifiStatus = WL_IDLE_STATUS;40WiFiUDP Udp; // A UDP instance to let us send and receive packets over UDP41NTPClient timeClient(Udp);42
43void printWifiStatus() {44 // print the SSID of the network you're attached to:45 Serial.print("SSID: ");46 Serial.println(WiFi.SSID());47
48 // print your board's IP address:49 IPAddress ip = WiFi.localIP();50 Serial.print("IP Address: ");51 Serial.println(ip);52
53 // print the received signal strength:54 long rssi = WiFi.RSSI();55 Serial.print("signal strength (RSSI):");56 Serial.print(rssi);57 Serial.println(" dBm");58}59
60void connectToWiFi(){61 // check for the WiFi module:62 if (WiFi.status() == WL_NO_MODULE) {63 Serial.println("Communication with WiFi module failed!");64 // don't continue65 while (true);66 }67
68 String fv = WiFi.firmwareVersion();69 if (fv < WIFI_FIRMWARE_LATEST_VERSION) {70 Serial.println("Please upgrade the firmware");71 }72
73 // attempt to connect to WiFi network:74 while (wifiStatus != WL_CONNECTED) {75 Serial.print("Attempting to connect to SSID: ");76 Serial.println(ssid);77 // Connect to WPA/WPA2 network. Change this line if using open or WEP network:78 wifiStatus = WiFi.begin(ssid, pass);79
80 // wait 10 seconds for connection:81 delay(10000);82 }83
84 Serial.println("Connected to WiFi");85 printWifiStatus();86}87
88void setup(){89 Serial.begin(9600);90 while (!Serial);91
92 connectToWiFi();93 RTC.begin();94 Serial.println("\nStarting connection to server...");95 timeClient.begin();96 timeClient.update();97
98 // Get the current date and time from an NTP server and convert99 // it to UTC +2 by passing the time zone offset in hours.100 // You may change the time zone offset to your local one.101 auto timeZoneOffsetHours = 2;102 auto unixTime = timeClient.getEpochTime() + (timeZoneOffsetHours * 3600);103 Serial.print("Unix time = ");104 Serial.println(unixTime);105 RTCTime timeToSet = RTCTime(unixTime);106 RTC.setTime(timeToSet);107
108 // Retrieve the date and time from the RTC and print them109 RTCTime currentTime;110 RTC.getTime(currentTime); 111 Serial.println("The RTC was just set to: " + String(currentTime));112}113
114void loop(){}115
Please also note that you will need to create a new tab called
arduino_secrets.h
. This is used to store your credentials. In this file, you will need to add:1#define SECRET_SSID "" //network name2#define SECRET_PASS "" //network password
Summary
This tutorial shows how to use the RTC on the UNO R4 WiFi, such as setting a start time, setting an alarm, or obtaining time in calendar or unix format.
Read more about this board in the Arduino UNO R4 WiFi documentation.
Suggest changes
The content on docs.arduino.cc is facilitated through a public GitHub repository. If you see anything wrong, you can edit this page here.
License
The Arduino documentation is licensed under the Creative Commons Attribution-Share Alike 4.0 license.