Arduino UNO R4 WiFi Bluetooth RTC Voorbeeld - Real-Time Clock Sync via BLE Tutorial
Overzicht
Het Bluetooth RTC voorbeeld biedt real-time kloksynchronisatie via de DIYables Bluetooth STEM app. Ontworpen voor Arduino UNO R4 WiFi die BLE (Bluetooth Low Energy) gebruikt om de ingebouwde hardware RTC van het board te synchroniseren met de klok van uw smartphone en de tijd weer te geven. De Arduino UNO R4 WiFi heeft een ingebouwde RTC module, waardoor het ideaal is voor tijdhouding projecten zonder externe RTC hardware nodig te hebben. Perfect voor klokken, data logging met timestamps, geplande automatisering en tijdgebaseerde projecten.
Opmerking: De Arduino UNO R4 WiFi ondersteunt alleen BLE (Bluetooth Low Energy). Het ondersteunt geen Classic Bluetooth. De DIYables Bluetooth App ondersteunt zowel BLE als Classic Bluetooth op Android, en BLE op iOS. Aangezien dit board BLE gebruikt, werkt de app op zowel Android als iOS.
Functies
Ingebouwde Hardware RTC: Gebruikt Arduino UNO R4 WiFi's onboard RTC — geen externe module nodig
Telefoon Tijdsync: Synchroniseer tijd van smartphone via Unix timestamp of lokale tijdcomponenten
Real-Time Weergave: Toon huidige tijd op de app, elke seconde bijgewerkt
Tijdaanvraag: App kan huidige tijd van het board opvragen
Persistente Tijdhouding: RTC houdt tijd bij terwijl board gevoed wordt
Werkt op Android & iOS: BLE wordt ondersteund op beide platforms
Geen Koppeling Vereist: BLE verbindt automatisch zonder handmatige koppeling
Openbaarmaking: Sommige van de links in deze sectie zijn Amazon-affiliate links. We kunnen een commissie ontvangen voor aankopen die via deze links worden gedaan, zonder extra kosten voor u. We waarderen uw steun.
Opmerking: Geen externe RTC module is nodig! De Arduino UNO R4 WiFi heeft een ingebouwde hardware RTC toegankelijk via de RTC.h bibliotheek.
Verbind het Arduino UNO R4 WiFi board met uw computer via een USB-kabel.
Start de Arduino IDE op uw computer.
Selecteer Arduino UNO R4 WiFi board en de juiste COM-poort.
Navigeer naar het Libraries icoon in de linkerbalk van de Arduino IDE.
Zoek "DIYables Bluetooth", vind vervolgens de DIYables Bluetooth bibliotheek van DIYables
Klik op de Install knop om de bibliotheek te installeren.
U wordt gevraagd om enkele andere bibliotheekafhankelijkheden te installeren
Klik op de Install All knop om alle bibliotheekafhankelijkheden te installeren.
BLE Code
In Arduino IDE, ga naar File Examples DIYables Bluetooth ArduinoBLE_RTC voorbeeld, of kopieer de bovenstaande code en plak het in de editor van Arduino IDE
/* * DIYables Bluetooth Library - Bluetooth RTC Example * Works with DIYables Bluetooth STEM app on Android and iOS * * This example demonstrates the Bluetooth RTC (Real-Time Clock) feature: * - Real-time clock display for both Arduino and mobile app * - One-click time synchronization from mobile app to Arduino * - Hardware RTC integration for persistent timekeeping * - Visual time difference monitoring * * Compatible Boards: * - Arduino UNO R4 WiFi (with built-in RTC) * Note: This example requires a board with hardware RTC. * Other BLE boards can be used with an external RTC module (e.g., DS3231). * * Setup: * 1. Upload the sketch to your Arduino * 2. Open Serial Monitor to see connection status * 3. Use DIYables Bluetooth App to connect and sync time * * Tutorial: https://diyables.io/bluetooth-app * Author: DIYables */#include <DIYables_BluetoothServer.h>#include <DIYables_BluetoothRTC.h>#include <platforms/DIYables_ArduinoBLE.h>#include"RTC.h"// BLE Configurationconst char* DEVICE_NAME = "Arduino_RTC";const char* SERVICE_UUID = "19B10000-E8F2-537E-4F6C-D104768A1214";const char* TX_UUID = "19B10001-E8F2-537E-4F6C-D104768A1214";const char* RX_UUID = "19B10002-E8F2-537E-4F6C-D104768A1214";// Create Bluetooth instancesDIYables_ArduinoBLE bluetooth(DEVICE_NAME, SERVICE_UUID, TX_UUID, RX_UUID);DIYables_BluetoothServer bluetoothServer(bluetooth);// Create RTC app instanceDIYables_BluetoothRTC bluetoothRTC;voidsetup() {Serial.begin(9600);delay(1000);Serial.println("DIYables Bluetooth - RTC Example");// Initialize RTC RTC.begin();// Check if RTC is running and set initial time if needed RTCTime savedTime; RTC.getTime(savedTime);if (!RTC.isRunning() || savedTime.getYear() == 2000) {Serial.println("RTC is NOT running, setting initial time...");// Set a default time - you can modify this to match current time RTCTime startTime(28, Month::AUGUST, 2025, 12, 0, 0, DayOfWeek::THURSDAY, SaveLight::SAVING_TIME_ACTIVE); RTC.setTime(startTime);Serial.println("RTC initialized with default time"); } else {Serial.println("RTC is already running"); }// Print initial RTC time RTCTime initialTime; RTC.getTime(initialTime);Serial.print("Initial RTC Time: ");Serial.print(initialTime.getYear());Serial.print("/");Serial.print(Month2int(initialTime.getMonth()));Serial.print("/");Serial.print(initialTime.getDayOfMonth());Serial.print(" - ");if (initialTime.getHour() < 10) Serial.print("0");Serial.print(initialTime.getHour());Serial.print(":");if (initialTime.getMinutes() < 10) Serial.print("0");Serial.print(initialTime.getMinutes());Serial.print(":");if (initialTime.getSeconds() < 10) Serial.print("0");Serial.print(initialTime.getSeconds());Serial.println();// Initialize Bluetooth server with platform-specific implementation bluetoothServer.begin();// Add RTC app to server bluetoothServer.addApp(&bluetoothRTC);// Set up connection event callbacks bluetoothServer.setOnConnected([]() {Serial.println("Bluetooth connected!");// Send current time to app on connection sendCurrentTimeToApp(); }); bluetoothServer.setOnDisconnected([]() {Serial.println("Bluetooth disconnected!"); });// Set callback for time sync from mobile app (Unix timestamp) bluetoothRTC.onTimeSync(onTimeSyncReceived);// Set callback for local time sync from mobile app (date/time components) bluetoothRTC.onLocalTimeSync(onLocalTimeSyncReceived);// Set callback for time request from mobile app bluetoothRTC.onTimeRequest(onTimeRequested);Serial.println("Waiting for Bluetooth connection...");Serial.println("Connect via app to sync time");}voidloop() {// Handle Bluetooth server communications bluetoothServer.loop();// Send current time to mobile app and print to Serial every 1 secondstaticunsignedlong lastUpdate = 0;if (millis() - lastUpdate >= 1000) { lastUpdate = millis();// Get current RTC time RTCTime currentTime; RTC.getTime(currentTime);// Send time to mobile app in human readable format bluetoothRTC.sendTime(currentTime.getYear(), Month2int(currentTime.getMonth()), currentTime.getDayOfMonth(), currentTime.getHour(), currentTime.getMinutes(), currentTime.getSeconds());// Print time to Serial MonitorSerial.print("RTC Time: ");Serial.print(currentTime.getYear());Serial.print("/");Serial.print(Month2int(currentTime.getMonth()));Serial.print("/");Serial.print(currentTime.getDayOfMonth());Serial.print(" - ");if (currentTime.getHour() < 10) Serial.print("0");Serial.print(currentTime.getHour());Serial.print(":");if (currentTime.getMinutes() < 10) Serial.print("0");Serial.print(currentTime.getMinutes());Serial.print(":");if (currentTime.getSeconds() < 10) Serial.print("0");Serial.print(currentTime.getSeconds());Serial.println(); }delay(10);}// Callback function called when mobile app sends time sync commandvoid onTimeSyncReceived(unsignedlong unixTimestamp) {Serial.print("Time sync received (Unix): ");Serial.println(unixTimestamp);// Convert Unix timestamp to RTCTime RTCTime newTime; newTime.setUnixTime(unixTimestamp);// Set RTC time RTC.setTime(newTime);Serial.println("Arduino RTC synchronized from Unix timestamp!");}// Callback function called when mobile app sends local time sync with componentsvoid onLocalTimeSyncReceived(intyear, intmonth, intday, inthour, intminute, intsecond) {Serial.print("Local time sync received: ");Serial.print(year);Serial.print("/");Serial.print(month);Serial.print("/");Serial.print(day);Serial.print(" ");Serial.print(hour);Serial.print(":");Serial.print(minute);Serial.print(":");Serial.println(second);// Create RTCTime from components (local time)// Convert month integer to Month enum Month monthEnum;switch(month) {case 1: monthEnum = Month::JANUARY; break;case 2: monthEnum = Month::FEBRUARY; break;case 3: monthEnum = Month::MARCH; break;case 4: monthEnum = Month::APRIL; break;case 5: monthEnum = Month::MAY; break;case 6: monthEnum = Month::JUNE; break;case 7: monthEnum = Month::JULY; break;case 8: monthEnum = Month::AUGUST; break;case 9: monthEnum = Month::SEPTEMBER; break;case 10: monthEnum = Month::OCTOBER; break;case 11: monthEnum = Month::NOVEMBER; break;case 12: monthEnum = Month::DECEMBER; break;default: monthEnum = Month::JANUARY; break; } RTCTime newTime(day, monthEnum, year, hour, minute, second, DayOfWeek::MONDAY, SaveLight::SAVING_TIME_ACTIVE);// Set RTC time RTC.setTime(newTime);Serial.println("Arduino RTC synchronized from local time components!");}// Callback function called when mobile app requests current Arduino timevoid onTimeRequested() {Serial.println("Time requested by app"); sendCurrentTimeToApp();}// Helper function to send current time to mobile appvoid sendCurrentTimeToApp() {// Get current RTC time and send to app in human readable format RTCTime currentTime; RTC.getTime(currentTime); bluetoothRTC.sendTime(currentTime.getYear(), Month2int(currentTime.getMonth()), currentTime.getDayOfMonth(), currentTime.getHour(), currentTime.getMinutes(), currentTime.getSeconds());}
Klik op de Upload knop in Arduino IDE om code naar Arduino UNO R4 WiFi te uploaden
Open de Serial Monitor
Bekijk het resultaat in de Serial Monitor. Het ziet er als volgt uit:
Newbiely | Arduino IDE 2.3.8
──
☐
✕
File
Edit
Sketch
Tools
Help
Arduino Uno R4 WiFi
Newbiely.ino
···
8Serial.println("Hello World!");
Output
Serial Monitor
Message (Enter to send message to 'Arduino Uno R4 WiFi' on 'COM15')
New Line
9600 baud
DIYables Bluetooth - RTC Example
Waiting for Bluetooth connection...
RTC not running or year is 2000, waiting for time sync...
Ln 11, Col 1
Arduino Uno R4 WiFi on COM15
2
Mobiele App
Installeer de DIYables Bluetooth App op uw smartphone: Android | iOS
Opmerking: De DIYables Bluetooth App ondersteunt zowel BLE als Classic Bluetooth op Android, en BLE op iOS. Aangezien de Arduino UNO R4 WiFi BLE gebruikt, werkt de app op zowel Android als iOS. Handmatige koppeling is niet nodig voor BLE — gewoon scannen en verbinden.
Open de DIYables Bluetooth App
Bij het eerste gebruik van de app vraagt het om machtigingen. Verleen de volgende:
Nearby Devices machtiging (Android 12+) / Bluetooth machtiging (iOS) - vereist om Bluetooth apparaten te scannen en verbinden
Location machtiging (alleen Android 11 en lager) - vereist door oudere Android versies om BLE apparaten te scannen
Zorg ervoor dat Bluetooth is ingeschakeld op uw telefoon
Tik op het beginscherm op de Connect knop. De app zal scannen naar BLE apparaten.
Vind en tik op "Arduino_RTC" in de scanresultaten om te verbinden.
Eenmaal verbonden, gaat de app automatisch terug naar het beginscherm. Selecteer de RTC app uit het app-menu.
Opmerking: U kunt op het instellingen icoon op het beginscherm tikken om apps te verbergen/tonen op het beginscherm. Voor meer details, zie de DIYables Bluetooth App Gebruikershandleiding.
De app zal de huidige tijd van de Arduino's RTC weergeven
Gebruik de Sync knop om de tijd van de telefoon naar de Arduino te synchroniseren
De tijd wordt elke seconde bijgewerkt
Kijk nu terug naar de Serial Monitor in Arduino IDE. U zult zien:
Newbiely | Arduino IDE 2.3.8
──
☐
✕
File
Edit
Sketch
Tools
Help
Arduino Uno R4 WiFi
Newbiely.ino
···
8Serial.println("Hello World!");
Output
Serial Monitor
Message (Enter to send message to 'Arduino Uno R4 WiFi' on 'COM15')
New Line
9600 baud
Bluetooth connected!
Time sync received (unix): 1719849600
RTC set to: 2025/07/01 12:00:00
Current time: 2025/07/01 12:00:01
Current time: 2025/07/01 12:00:02
Ln 11, Col 1
Arduino Uno R4 WiFi on COM15
2
Creatieve Aanpassing - Pas de Code aan voor Uw Project
Tijdsync Methoden
De app kan tijd naar de Arduino synchroniseren met twee methoden:
// Methode 1: Unix timestamp syncbluetoothRTC.onTimeSync([](unsignedlong unixTime) {// Converteer Unix timestamp en stel RTC inSerial.print("Unix time: ");Serial.println(unixTime);});// Methode 2: Lokale tijdcomponenten syncbluetoothRTC.onLocalTimeSync([](intyear, intmonth, intday, inthour, intminute, intsecond) {// Stel RTC direct in met componentenSerial.print("Local time: ");Serial.print(year);Serial.print("/");Serial.print(month);Serial.print("/");Serial.println(day);});
Tijd Verzenden naar App
// Verstuur huidige tijd naar de appbluetoothRTC.sendTime(year, month, day, hour, minute, second);
Tijdaanvragen Behandelen
bluetoothRTC.onTimeRequest([]() {// App vraagt om de huidige tijd// Lees RTC en verstuur tijd terug RTCTime currentTime; RTC.getTime(currentTime); bluetoothRTC.sendTime( currentTime.getYear(), Month2int(currentTime.getMonth()), currentTime.getDayOfMonth(), currentTime.getHour(), currentTime.getMinutes(), currentTime.getSeconds() );});
Gebruik van de Ingebouwde RTC
De ingebouwde RTC van de Arduino UNO R4 WiFi wordt benaderd via de RTC.h bibliotheek:
#include"RTC.h"voidsetup() { RTC.begin(); // Initialiseer de hardware RTC}// Stel tijd in op de RTCRTCTime timeToSet;timeToSet.setYear(2025);timeToSet.setMonth(Month::JULY);timeToSet.setDayOfMonth(1);timeToSet.setHour(12);timeToSet.setMinute(0);timeToSet.setSecond(0);RTC.setTime(timeToSet);// Lees tijd van de RTCRTCTime currentTime;RTC.getTime(currentTime);intyear = currentTime.getYear();intmonth = Month2int(currentTime.getMonth());intday = currentTime.getDayOfMonth();inthour = currentTime.getHour();intminute = currentTime.getMinutes();intsecond = currentTime.getSeconds();
U bent welkom om de link naar deze tutorial te delen. Gebruik onze inhoud echter niet op andere websites. We hebben veel moeite en tijd gestoken in het maken van de inhoud, respecteer alstublieft ons werk!