Arduino UNO R4 WiFi Bluetooth Chat Voorbeeld - Tweerichtings Berichten via BLE Tutorial

Overzicht

Het Bluetooth Chat voorbeeld biedt een tweerichtings tekstberichten-interface die toegankelijk is via de DIYables Bluetooth STEM app. Ontworpen voor Arduino UNO R4 WiFi met BLE (Bluetooth Low Energy) om in realtime tekstberichten te verzenden en ontvangen tussen uw Arduino en smartphone. Perfect voor commandoregel-interfaces, bediening op afstand via tekstcommando's, seriële bridges en interactieve debugging.

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. Omdat dit board BLE gebruikt, werkt de app op zowel Android als iOS.

Arduino UNO R4 WiFi Bluetooth Chat Voorbeeld - Tweerichtings Berichten via BLE Tutorial

Eigenschappen

  • Tweerichtings Berichten: Verzend en ontvang tekstberichten in realtime
  • Commando Verwerking: Verwerk tekstcommando's vanuit de mobiele app
  • Seriële Bridge: Doorstuur berichten tussen Serial Monitor en Bluetooth
  • Aangepaste Reacties: Automatisch antwoorden met echo's of verwerkte data
  • Werkt op Android & iOS: BLE wordt ondersteund op beide platforms
  • Geen Pairing Vereist: BLE verbindt automatisch zonder handmatige koppeling
  • Laag Stroomverbruik: BLE verbruikt minder stroom dan Classic Bluetooth

Arduino UNO R4 WiFi Code

Snelle Stappen

Volg deze instructies stap voor stap:

  • Als dit uw eerste keer is met de Arduino UNO R4 WiFi, raadpleeg de Arduino UNO R4 WiFi aan de slag gids.
  • Sluit het Arduino UNO R4 WiFi board aan op uw computer met 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 linker balk van de Arduino IDE.
  • Zoek "DIYables Bluetooth", vind dan de DIYables Bluetooth bibliotheek door DIYables
  • Klik op de Install knop om de bibliotheek te installeren.
Arduino UNO R4 DIYables Bluetooth library
  • U wordt gevraagd om enkele andere bibliotheekafhankelijkheden te installeren
  • Klik op de Install All knop om alle bibliotheekafhankelijkheden te installeren.
Arduino UNO R4 DIYables Bluetooth dependency

BLE Code

  • In Arduino IDE, ga naar File Examples DIYables Bluetooth ArduinoBLE_Chat voorbeeld, of kopieer de bovenstaande code en plak deze in de editor van Arduino IDE
/* * DIYables Bluetooth Library - Bluetooth Chat Example * Works with DIYables Bluetooth STEM app on Android and iOS * * This example demonstrates the Bluetooth Chat feature: * - Two-way text messaging via Bluetooth * - Receive messages from mobile app * - Send messages to mobile app * * Compatible Boards: * - Arduino UNO R4 WiFi * - Arduino Nano 33 BLE / BLE Sense * - Arduino Nano 33 IoT * - Arduino MKR WiFi 1010 * - Arduino Nano RP2040 Connect * - Any board supporting the ArduinoBLE library * * Setup: * 1. Upload the sketch to your Arduino * 2. Open Serial Monitor to see connection status and messages * 3. Use DIYables Bluetooth App to connect and chat * * Tutorial: https://diyables.io/bluetooth-app * Author: DIYables */ #include <DIYables_BluetoothServer.h> #include <DIYables_BluetoothChat.h> #include <platforms/DIYables_ArduinoBLE.h> // BLE Configuration const char* DEVICE_NAME = "Arduino_Chat"; 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 instances DIYables_ArduinoBLE bluetooth(DEVICE_NAME, SERVICE_UUID, TX_UUID, RX_UUID); DIYables_BluetoothServer bluetoothServer(bluetooth); // Create Chat app instance DIYables_BluetoothChat bluetoothChat; // Variables for periodic messages unsigned long lastMessageTime = 0; const unsigned long MESSAGE_INTERVAL = 10000; // Send message every 10 seconds int messageCount = 0; void setup() { Serial.begin(9600); while (!Serial); Serial.println("DIYables Bluetooth - Chat Example"); // Initialize Bluetooth server with platform-specific implementation bluetoothServer.begin(); // Add chat app to server bluetoothServer.addApp(&bluetoothChat); // Set up connection event callbacks bluetoothServer.setOnConnected([]() { Serial.println("Bluetooth connected!"); bluetoothChat.send("Hello! Arduino is ready to chat."); }); bluetoothServer.setOnDisconnected([]() { Serial.println("Bluetooth disconnected!"); messageCount = 0; }); // Set up callback for received chat messages bluetoothChat.onChatMessage([](const String& message) { Serial.print("Received: "); Serial.println(message); // Echo the message back String response = "Echo: "; response += message; bluetoothChat.send(response); // You can add custom command handling here if (message.equalsIgnoreCase("ping")) { bluetoothChat.send("pong!"); } else if (message.equalsIgnoreCase("status")) { bluetoothChat.send("Arduino is running normally"); } else if (message.equalsIgnoreCase("time")) { String timeMsg = "Uptime: "; timeMsg += String(millis() / 1000); timeMsg += " seconds"; bluetoothChat.send(timeMsg); } }); Serial.println("Waiting for Bluetooth connection..."); Serial.println("Type 'ping', 'status', or 'time' in the app to test commands"); } void loop() { // Handle Bluetooth server communications bluetoothServer.loop(); // Send periodic status message (only when connected) if (bluetooth.isConnected() && millis() - lastMessageTime >= MESSAGE_INTERVAL) { lastMessageTime = millis(); messageCount++; String statusMsg = "Status update #"; statusMsg += String(messageCount); statusMsg += " - All systems operational"; bluetoothChat.send(statusMsg); Serial.print("Sent: "); Serial.println(statusMsg); } // Optional: Read from Serial and send to Bluetooth if (Serial.available()) { String serialMsg = Serial.readStringUntil('\n'); serialMsg.trim(); if (serialMsg.length() > 0 && bluetooth.isConnected()) { bluetoothChat.send(serialMsg); Serial.print("Sent from Serial: "); Serial.println(serialMsg); } } delay(10); }
  • Klik op de Upload knop in Arduino IDE om de code naar Arduino UNO R4 WiFi te uploaden
  • Open de Serial Monitor
  • Bekijk het resultaat in Serial Monitor. Het ziet er als volgt uit:
COM6
Send
DIYables Bluetooth - Chat Example Waiting for Bluetooth connection...
Autoscroll Show timestamp
Clear output
9600 baud  
Newline  

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. Omdat 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 worden er toestemmingen gevraagd. Verleen de volgende toestemmingen:
    • Nearby Devices toestemming (Android 12+) / Bluetooth toestemming (iOS) - vereist om Bluetooth-apparaten te scannen en er verbinding mee te maken
    • Locatie toestemming (alleen Android 11 en eerder) - vereist door oudere Android-versies om BLE-apparaten te scannen
  • Zorg ervoor dat Bluetooth is ingeschakeld op uw telefoon
  • Tik op het startscherm op de Connect knop. De app zal scannen naar BLE-apparaten.
DIYables Bluetooth App - Home Screen with Scan Button
  • Zoek en tik op "Arduino_Chat" in de scanresultaten om verbinding te maken.
  • Eenmaal verbonden gaat de app automatisch terug naar het startscherm. Selecteer de Chat app uit het app-menu.
DIYables Bluetooth App - Home Screen with Chat App

Opmerking: U kunt op het instellingen-icoon op het startscherm tikken om apps op het startscherm te verbergen/tonen. Voor meer details, zie de DIYables Bluetooth App Gebruikershandleiding.

  • Typ een bericht in het chat-invoerveld en tik op verzenden
DIYables Bluetooth App - Chat Screen

Kijk nu terug naar de Serial Monitor in Arduino IDE. U zult zien:

COM6
Send
Bluetooth connected! Received: Hello
Autoscroll Show timestamp
Clear output
9600 baud  
Newline  
  • De Arduino echoot uw bericht terug, en u kunt het antwoord zien in de app chat

Creatieve Aanpassing - Pas de Code Aan voor Uw Project

Chat Berichten Verwerken

Gebruik de onChatMessage() callback om berichten te ontvangen en verwerken die in de app getypt worden. U kunt aangepaste commando-woorden definiëren die logisch zijn voor uw project — de Arduino zal dienovereenkomstig reageren:

bluetoothChat.onChatMessage([](const String& message) { Serial.print("Received: "); Serial.println(message); // Echo the message back String response = "Echo: "; response += message; bluetoothChat.send(response); // Handle custom commands if (message.equalsIgnoreCase("ping")) { bluetoothChat.send("pong!"); } else if (message.equalsIgnoreCase("status")) { bluetoothChat.send("Arduino is running normally"); } else if (message.equalsIgnoreCase("time")) { String timeMsg = "Uptime: " + String(millis() / 1000) + " seconds"; bluetoothChat.send(timeMsg); } else { bluetoothChat.send("Unknown command: " + message); } });

U kunt zoveel aangepaste commando's toevoegen als u nodig heeft door meer else if blokken toe te voegen. Voeg bijvoorbeeld LED_ON / LED_OFF toe om een pin te besturen, of READ om een sensor-uitlezing te activeren — elk woord dat u in de app typt wordt een commando.

Berichten Verzenden vanuit Arduino

// Send a text message to the app bluetoothChat.send("Hello from Arduino!"); // Send sensor reading float temp = readTemperature(); bluetoothChat.send("Temperature: " + String(temp, 1) + " °C");

Serial-naar-Bluetooth Bridge

Doorstuur berichten tussen Serial Monitor en Bluetooth:

// In loop(): if (Serial.available()) { String serialMsg = Serial.readStringUntil('\n'); serialMsg.trim(); if (serialMsg.length() > 0 && bluetooth.isConnected()) { bluetoothChat.send(serialMsg); Serial.print("Sent from Serial: "); Serial.println(serialMsg); } }

Verbindingsgebeurtenissen Verwerken

bluetoothServer.setOnConnected([]() { Serial.println("Bluetooth connected!"); bluetoothChat.send("Hello! Arduino is ready to chat."); }); bluetoothServer.setOnDisconnected([]() { Serial.println("Bluetooth disconnected!"); });

Hoe de Chat te Gebruiken

App Interface

De chat-interface in de DIYables Bluetooth App biedt:

  • Berichtenlijst: Toont verzonden en ontvangen berichten met tijdstempels
  • Tekstinvoer: Typ berichten om naar de Arduino te verzenden
  • Verzend Knop: Tik om het bericht te verzenden

Communicatieflow

  1. Typ een bericht in de app → Arduino ontvangt het via onChatMessage() callback
  2. Arduino verwerkt het bericht en stuurt optioneel een antwoord via bluetoothChat.send()
  3. Het antwoord verschijnt in het app chatvenster

Programmeervoorbeelden

Commandoverwerker met Relais Besturing

const int RELAY_PIN = 7; bluetoothChat.onChatMessage([](const String& message) { String cmd = message; cmd.toUpperCase(); if (cmd == "ON") { digitalWrite(RELAY_PIN, HIGH); bluetoothChat.send("Relay turned ON"); } else if (cmd == "OFF") { digitalWrite(RELAY_PIN, LOW); bluetoothChat.send("Relay turned OFF"); } else if (cmd == "STATUS") { int state = digitalRead(RELAY_PIN); bluetoothChat.send("Relay is " + String(state ? "ON" : "OFF")); } else { bluetoothChat.send("Commands: ON, OFF, STATUS"); } });

Sensor Query Systeem

bluetoothChat.onChatMessage([](const String& message) { String cmd = message; cmd.toUpperCase(); if (cmd == "TEMP") { float temp = readTemperature(); bluetoothChat.send("Temperature: " + String(temp, 1) + " °C"); } else if (cmd == "LIGHT") { int light = analogRead(A0); int percent = map(light, 0, 1023, 0, 100); bluetoothChat.send("Light level: " + String(percent) + "%"); } else if (cmd == "ALL") { bluetoothChat.send("=== Sensor Report ==="); bluetoothChat.send("Temp: " + String(readTemperature(), 1) + " °C"); bluetoothChat.send("Light: " + String(map(analogRead(A0), 0, 1023, 0, 100)) + "%"); bluetoothChat.send("Uptime: " + String(millis() / 1000) + "s"); } else { bluetoothChat.send("Commands: TEMP, LIGHT, ALL"); } });

Periodieke Status Updates

unsigned long lastMessageTime = 0; const unsigned long MESSAGE_INTERVAL = 10000; // Every 10 seconds int messageCount = 0; void loop() { bluetoothServer.loop(); if (bluetooth.isConnected() && millis() - lastMessageTime >= MESSAGE_INTERVAL) { lastMessageTime = millis(); messageCount++; String statusMsg = "Status #" + String(messageCount) + " - All systems OK"; bluetoothChat.send(statusMsg); } delay(10); }

Geavanceerde Programmeertechnieken

Meerdere-Woorden Commando Parsing

bluetoothChat.onChatMessage([](const String& message) { // Parse "SET PIN 13 HIGH" style commands if (message.startsWith("SET PIN ")) { String rest = message.substring(8); int spaceIdx = rest.indexOf(' '); if (spaceIdx > 0) { int pin = rest.substring(0, spaceIdx).toInt(); String state = rest.substring(spaceIdx + 1); state.toUpperCase(); pinMode(pin, OUTPUT); if (state == "HIGH") { digitalWrite(pin, HIGH); bluetoothChat.send("Pin " + String(pin) + " set HIGH"); } else if (state == "LOW") { digitalWrite(pin, LOW); bluetoothChat.send("Pin " + String(pin) + " set LOW"); } } } });

Chat Logger met Tijdstempels

bluetoothChat.onChatMessage([](const String& message) { unsigned long seconds = millis() / 1000; String timestamp = "[" + String(seconds / 3600) + ":" + String((seconds % 3600) / 60) + ":" + String(seconds % 60) + "] "; Serial.println(timestamp + "RX: " + message); // Log and acknowledge bluetoothChat.send(timestamp + "Received: " + message); });

Probleemoplossing

Veelvoorkomende Problemen

1. Kan het apparaat niet vinden in de app

  • Zorg ervoor dat de Arduino UNO R4 WiFi is ingeschakeld en de sketch is geüpload
  • Controleer of Bluetooth op uw telefoon is ingeschakeld
  • Op Android 11 en eerder, schakel ook Locatiediensten in
  • Probeer Bluetooth op uw telefoon opnieuw op te starten

2. Berichten worden niet ontvangen door Arduino

  • Controleer de Bluetooth-verbindingsstatus in de app
  • Verifieer dat de onChatMessage callback correct is ingesteld
  • Controleer Serial Monitor op foutmeldingen

3. Arduino antwoorden verschijnen niet in app

  • Zorg ervoor dat bluetoothChat.send() wordt aangeroepen
  • Controleer dat bluetoothServer.loop() wordt aangeroepen in de hoofdlus
  • Verifieer dat de verbinding nog actief is met bluetooth.isConnected()

4. Serial Monitor toont onleesbare tekst

  • Zorg ervoor dat de baudrate in Serial Monitor overeenkomt met Serial.begin(9600)
  • Controleer dat het juiste board is geselecteerd in Arduino IDE

5. Verbinding valt vaak weg

  • Ga dichter bij de Arduino staan (afstand verkleinen)
  • Controleer op interferentie van andere BLE-apparaten
  • Zorg voor stabiele USB-stroomvoorziening

6. Upload mislukt of board wordt niet herkend

  • Installeer het nieuwste Arduino UNO R4 board pakket via Board Manager
  • Probeer een andere USB-kabel of poort
  • Druk op de reset-knop op het board voordat u uploadt

Projectideeën

Communicatie

  • Tekstcommando-interface voor domotica
  • Serial-naar-Bluetooth bridge voor draadloze debugging
  • Remote sensor query systeem
  • Interactieve quiz of trivia spel

Besturingssystemen

  • Spraak-naar-tekst relais besturing
  • Multi-apparaat commando router
  • Configuratie manager via chat commando's
  • Firmware versie reporter

Logging & Monitoring

  • Gebeurtenislogger met tijdstempels
  • Alarm notificatiesysteem
  • Status rapport generator
  • Diagnostische chat bot

Integratie met Andere Bluetooth Apps

Combineren met Bluetooth Monitor

Gebruik chat voor commando's en monitor voor continue uitvoer:

bluetoothChat.onChatMessage([](const String& message) { if (message == "START") { monitoring = true; bluetoothChat.send("Monitoring started"); } else if (message == "STOP") { monitoring = false; bluetoothChat.send("Monitoring stopped"); } }); // In loop: if (monitoring) { bluetoothMonitor.send("Sensor: " + String(analogRead(A0))); }

Combineren met Bluetooth Table

Chat commando's om te controleren welke data in de tabel wordt getoond:

bluetoothChat.onChatMessage([](const String& message) { if (message == "REFRESH") { updateTableValues(); bluetoothChat.send("Table refreshed"); } });

Volgende Stappen

Na het beheersen van het Bluetooth Chat voorbeeld, probeer:

  1. Bluetooth Monitor - Voor eenrichtings status streaming
  2. Bluetooth Slider - Voor analoge waarde besturing
  3. Bluetooth Table - Voor gestructureerde data weergave
  4. Meerdere Bluetooth Apps - Chat combineren met andere apps

Ondersteuning

Voor aanvullende hulp:

  • Controleer de API Reference documentatie
  • Arduino community forums

※ ONZE BERICHTEN

  • 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!