Arduino UNO R4 WiFi Bluetooth Chat Example Giao Tiếp Hai Chiều qua BLE Tutorial

Tổng Quan

Ví dụ Bluetooth Chat cung cấp giao diện nhắn tin văn bản hai chiều có thể truy cập thông qua ứng dụng DIYables Bluetooth STEM. Được thiết kế cho Arduino UNO R4 WiFi sử dụng BLE (Bluetooth Low Energy) để gửi và nhận tin nhắn văn bản giữa Arduino và điện thoại thông minh của bạn trong thời gian thực. Hoàn hảo cho giao diện dòng lệnh, điều khiển từ xa thông qua lệnh văn bản, cầu nối serial, và gỡ lỗi tương tác.

Lưu ý: Arduino UNO R4 WiFi chỉ hỗ trợ BLE (Bluetooth Low Energy). Nó không hỗ trợ Classic Bluetooth. Ứng dụng DIYables Bluetooth hỗ trợ cả BLE và Classic Bluetooth trên Android, và BLE trên iOS. Vì bo mạch này sử dụng BLE, ứng dụng hoạt động trên cả Android và iOS.

Arduino UNO R4 WiFi Bluetooth chat example - giao tiếp hai chiều qua ble tutorial

Tính Năng

  • Nhắn Tin Hai Chiều: Gửi và nhận tin nhắn văn bản trong thời gian thực
  • Xử Lý Lệnh: Xử lý các lệnh văn bản từ ứng dụng di động
  • Cầu Nối Serial: Chuyển tiếp tin nhắn giữa Serial Monitor và Bluetooth
  • Phản Hồi Tùy Chỉnh: Tự động phản hồi với echo hoặc dữ liệu đã xử lý
  • Hoạt Động trên Android & iOS: BLE được hỗ trợ trên cả hai nền tảng
  • Không Cần Ghép Nối: BLE tự động kết nối mà không cần ghép nối thủ công
  • Tiết Kiệm Năng Lượng: BLE tiêu thụ ít năng lượng hơn Classic Bluetooth

Phần Cứng Cần Thiết

1×Arduino UNO R4 WiFi
1×Alternatively, DIYables STEM V4 IoT
1×(Tùy chọn) DIYables STEM V4 IoT
1×Cáp USB Type-C
1×(Khuyến nghị) Screw Terminal Block Shield for Arduino UNO R4
1×(Khuyến nghị) Breadboard Shield for Arduino UNO R4
1×(Khuyến nghị) Enclosure for Arduino UNO R4
1×(Khuyến nghị) Power Splitter for Arduino UNO R4
1×(Khuyến nghị) Prototyping Base Plate & Breadboard Kit for Arduino UNO

Or you can buy the following kits:

1×DIYables STEM V4 IoT Starter Kit (Arduino included)
1×DIYables Sensor Kit (30 sensors/displays)
1×DIYables Sensor Kit (18 sensors/displays)

Code Arduino UNO R4 WiFi

Các Bước Nhanh

Thực hiện theo hướng dẫn từng bước:

  • Nếu đây là lần đầu tiên bạn sử dụng Arduino UNO R4 WiFi, hãy tham khảo Arduino UNO R4 - Cài Đặt Phần Mềm.
  • Kết nối bo mạch Arduino UNO R4 WiFi với máy tính của bạn bằng cáp USB.
  • Khởi động Arduino IDE trên máy tính của bạn.
  • Chọn bo mạch Arduino UNO R4 WiFi và cổng COM phù hợp.
  • Điều hướng đến biểu tượng Libraries trên thanh bên trái của Arduino IDE.
  • Tìm kiếm "DIYables Bluetooth", sau đó tìm thư viện DIYables Bluetooth của DIYables
  • Nhấn nút Install để cài đặt thư viện.
Arduino UNO R4 diyables Bluetooth thư viện
  • Bạn sẽ được yêu cầu cài đặt một số thư viện phụ thuộc khác
  • Nhấn nút Install All để cài đặt tất cả thư viện phụ thuộc.
Arduino UNO R4 diyables Bluetooth dependency

Code BLE

  • Trên Arduino IDE, đi đến File Examples DIYables Bluetooth ArduinoBLE_Chat example, hoặc sao chép code trên và dán vào editor của 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); }
  • Nhấn nút Upload trên Arduino IDE để upload code lên Arduino UNO R4 WiFi
  • Mở Serial Monitor
  • Kiểm tra kết quả trên Serial Monitor. Nó sẽ trông như sau:
COM6
Send
DIYables Bluetooth - Chat Example Waiting for Bluetooth connection...
Autoscroll Show timestamp
Clear output
9600 baud  
Newline  

Ứng Dụng Di Động

  • Cài đặt ứng dụng DIYables Bluetooth trên điện thoại thông minh của bạn: Android | iOS

Lưu ý: Ứng dụng DIYables Bluetooth hỗ trợ cả BLE và Classic Bluetooth trên Android, và BLE trên iOS. Vì Arduino UNO R4 WiFi sử dụng BLE, ứng dụng hoạt động trên cả Android và iOS. Không cần ghép nối thủ công cho BLE — chỉ cần quét và kết nối.

  • Mở ứng dụng DIYables Bluetooth
  • Khi mở ứng dụng lần đầu tiên, nó sẽ yêu cầu quyền. Vui lòng cấp các quyền sau:
    • Quyền Nearby Devices (Android 12+) / quyền Bluetooth (iOS) - cần thiết để quét và kết nối với thiết bị Bluetooth
    • Quyền Location (chỉ Android 11 và thấp hơn) - cần thiết cho các phiên bản Android cũ để quét thiết bị BLE
  • Đảm bảo Bluetooth được bật trên điện thoại của bạn
  • Trên màn hình chính, chạm nút Connect. Ứng dụng sẽ quét các thiết bị BLE.
diyables Bluetooth app - home screen with scan nút nhấn
  • Tìm và chạm "Arduino_Chat" trong kết quả quét để kết nối.
  • Sau khi kết nối, ứng dụng tự động quay lại màn hình chính. Chọn ứng dụng Chat từ menu ứng dụng.
diyables Bluetooth app - home screen with chat app

Lưu ý: Bạn có thể chạm biểu tượng cài đặt trên màn hình chính để ẩn/hiện các ứng dụng trên màn hình chính. Để biết thêm chi tiết, hãy xem Hướng Dẫn Sử Dụng Ứng Dụng DIYables Bluetooth.

  • Nhập tin nhắn trong ô nhập chat và chạm gửi
diyables Bluetooth app - chat screen

Bây giờ hãy quay lại Serial Monitor trên Arduino IDE. Bạn sẽ thấy:

COM6
Send
Bluetooth connected! Received: Hello
Autoscroll Show timestamp
Clear output
9600 baud  
Newline  
  • Arduino echo lại tin nhắn của bạn, và bạn có thể thấy phản hồi trong chat ứng dụng

Tùy Chỉnh Sáng Tạo - Điều Chỉnh Code Cho Dự Án Của Bạn

Xử Lý Tin Nhắn Chat

Sử dụng callback onChatMessage() để nhận và xử lý tin nhắn được nhập trong ứng dụng. Bạn có thể định nghĩa bất kỳ từ lệnh tùy chỉnh nào phù hợp với dự án của bạn — Arduino sẽ phản ứng tương ứng:

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); } });

Bạn có thể thêm nhiều lệnh tùy chỉnh tùy ý bằng cách thêm các khối else if. Ví dụ, thêm LED_ON / LED_OFF để điều khiển một chân, hoặc READ để kích hoạt đọc sensor — bất kỳ từ nào bạn nhập trong ứng dụng đều trở thành lệnh.

Gửi Tin Nhắn từ 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");

Cầu Nối Serial-to-Bluetooth

Chuyển tiếp tin nhắn giữa Serial Monitor và 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); } }

Xử Lý Sự Kiện Kết Nối

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

Cách Sử Dụng Chat

Giao Diện Ứng Dụng

Giao diện chat trong ứng dụng DIYables Bluetooth cung cấp:

  • Danh Sách Tin Nhắn: Hiển thị tin nhắn đã gửi và nhận với dấu thời gian
  • Ô Nhập Văn Bản: Nhập tin nhắn để gửi cho Arduino
  • Nút Gửi: Chạm để gửi tin nhắn

Luồng Giao Tiếp

  1. Nhập tin nhắn trong ứng dụng → Arduino nhận qua callback onChatMessage()
  2. Arduino xử lý tin nhắn và tùy chọn gửi phản hồi qua bluetoothChat.send()
  3. Phản hồi xuất hiện trong cửa sổ chat ứng dụng

Ví Dụ Lập Trình

Xử Lý Lệnh với Điều Khiển Relay

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"); } });

Hệ Thống Truy Vấn Sensor

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"); } });

Cập Nhật Trạng Thái Định Kỳ

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); }

Kỹ Thuật Lập Trình Nâng Cao

Phân Tích Lệnh Nhiều Từ

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 với Dấu Thời Gian

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); });

Khắc Phục Sự Cố

Vấn Đề Thường Gặp

1. Không thể tìm thấy thiết bị trong ứng dụng

  • Đảm bảo Arduino UNO R4 WiFi được cấp nguồn và sketch đã được upload
  • Đảm bảo Bluetooth trên điện thoại được bật
  • Trên Android 11 và thấp hơn, cũng bật dịch vụ Vị trí
  • Thử khởi động lại Bluetooth trên điện thoại của bạn

2. Tin nhắn không được Arduino nhận

  • Kiểm tra trạng thái kết nối Bluetooth trong ứng dụng
  • Xác minh callback onChatMessage được thiết lập đúng
  • Kiểm tra Serial Monitor để xem có thông báo lỗi nào không

3. Phản hồi của Arduino không hiển thị trong ứng dụng

  • Đảm bảo bluetoothChat.send() đang được gọi
  • Kiểm tra rằng bluetoothServer.loop() được gọi trong vòng lặp chính
  • Xác minh kết nối vẫn hoạt động với bluetooth.isConnected()

4. Serial Monitor hiển thị văn bản lộn xộn

  • Đảm bảo baud rate trong Serial Monitor khớp với Serial.begin(9600)
  • Kiểm tra rằng bo mạch đúng đã được chọn trong Arduino IDE

5. Kết nối thường xuyên bị ngắt

  • Di chuyển gần Arduino hơn (giảm khoảng cách)
  • Kiểm tra nhiễu từ các thiết bị BLE khác
  • Đảm bảo nguồn cấp USB ổn định

6. Upload thất bại hoặc bo mạch không được nhận dạng

  • Cài đặt gói bo mạch Arduino UNO R4 mới nhất qua Board Manager
  • Thử cáp USB hoặc cổng khác
  • Nhấn nút reset trên bo mạch trước khi upload

Ý Tưởng Dự Án

Giao Tiếp

  • Giao diện lệnh văn bản cho tự động hóa nhà
  • Cầu nối Serial-to-Bluetooth cho gỡ lỗi không dây
  • Hệ thống truy vấn sensor từ xa
  • Trò chơi đố vui hoặc trivia tương tác

Hệ Thống Điều Khiển

  • Điều khiển relay qua lệnh voice-to-text
  • Bộ định tuyến lệnh đa thiết bị
  • Quản lý cấu hình qua lệnh chat
  • Báo cáo phiên bản firmware

Logging & Giám Sát

  • Event logger với dấu thời gian
  • Hệ thống thông báo cảnh báo
  • Trình tạo báo cáo trạng thái
  • Chat bot chẩn đoán

Tích Hợp với Các Ứng Dụng Bluetooth Khác

Kết Hợp với Bluetooth Monitor

Sử dụng chat cho lệnh và monitor cho đầu ra liên tục:

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))); }

Kết Hợp với Bluetooth Table

Lệnh chat để điều khiển dữ liệu hiển thị trong bảng:

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

Các Bước Tiếp Theo

Sau khi thành thạo ví dụ Bluetooth Chat, hãy thử:

  1. Bluetooth Monitor - Để truyền trạng thái một chiều
  2. Bluetooth Slider - Để điều khiển giá trị analog
  3. Bluetooth Table - Để hiển thị dữ liệu có cấu trúc
  4. Multiple Bluetooth Apps - Kết hợp chat với các ứng dụng khác

Hỗ Trợ

Để được trợ giúp thêm:

  • Kiểm tra tài liệu API Reference
  • Diễn đàn cộng đồng Arduino