ESP32 Bluetooth Table Example Hướng dẫn Giao diện Hiển thị Dữ liệu Có Cấu trúc
Tổng quan
Ví dụ Bluetooth Table cung cấp giao diện hiển thị dữ liệu key-value có cấu trúc được truy cập thông qua ứng dụng DIYables Bluetooth STEM. Được thiết kế cho các bo mạch ESP32 với hỗ trợ kết nối cả BLE (Bluetooth Low Energy) và Classic Bluetooth. Định nghĩa các hàng có tên và cập nhật giá trị theo thời gian thực — hoàn hảo cho dashboard, bảng trạng thái cảm biến, giám sát hệ thống, và bất kỳ ứng dụng nào yêu cầu trình bày dữ liệu có tổ chức.
Ví dụ này hỗ trợ hai chế độ Bluetooth:
ESP32 BLE (Bluetooth Low Energy): Hoạt động trên cả Android và iOS
ESP32 Classic Bluetooth: Chỉ hoạt động trên Android. iOS không hỗ trợ Classic Bluetooth. Sử dụng BLE nếu bạn cần hỗ trợ iOS.
Tính năng
Hàng Có Cấu trúc: Tối đa 20 hàng thuộc tính có tên
Cập Nhật Thời Gian Thực: Cập nhật giá trị từng hàng riêng lẻ mà không cần làm mới toàn bộ bảng
Thuộc Tính Có Tên: Mỗi hàng có một nhãn mô tả (ví dụ: "Temperature", "Status")
Giá Trị Động: Gửi bất kỳ giá trị chuỗi nào cho mỗi hàng
Đồng Bộ Cấu Trúc Bảng: Ứng dụng yêu cầu cấu hình bảng khi kết nối
BLE & Classic Bluetooth: Chọn chế độ Bluetooth phù hợp với dự án của bạn
Đa Nền Tảng: Chế độ BLE hoạt động trên cả Android và iOS; Classic Bluetooth hoạt động trên Android
Tùy Chọn Tiết Kiệm Pin: Chế độ BLE tiêu thụ ít năng lượng hơn Classic Bluetooth
Kết nối bo mạch ESP32 với máy tính của bạn bằng cáp USB.
Mở Arduino IDE trên máy tính của bạn.
Chọn bo mạch ESP32 và cổng COM phù hợp.
Điều hướng đến biểu tượng Libraries ở 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ấp nút Install để cài đặt 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ấp nút Install All để cài đặt tất cả thư viện phụ thuộc.
Chọn một trong hai chế độ Bluetooth bên dưới tùy theo nhu cầu của bạn:
Code ESP32 Classic Bluetooth (chỉ hoạt động với ứng dụng trên Android)
Lưu ý: Classic Bluetooth KHÔNG được hỗ trợ trên iOS. Nếu bạn cần hỗ trợ iOS, hãy sử dụng code BLE bên dưới.
Trên Arduino IDE, vào File Examples DIYables Bluetooth Esp32Bluetooth_Table example, hoặc sao chép code trên và dán vào editor của Arduino IDE
/* * DIYables Bluetooth Library - ESP32 Classic Bluetooth Table Example * Works with DIYables Bluetooth STEM app on Android * Note: Classic Bluetooth is NOT supported on iOS. Use BLE examples for iOS support. * * This example demonstrates the Bluetooth Table feature: * - Display structured data in a two-column table * - Real-time value updates for each row * - Perfect for sensor dashboards and status displays * * Compatible Boards: * - ESP32 (all variants with Classic Bluetooth) * - ESP32-WROOM-32 * - ESP32-DevKitC * - ESP32-WROVER * * Note: Select "Huge APP (3MB No OTA/1MB SPIFFS)" partition scheme * in Arduino IDE: Tools > Partition Scheme * * Setup: * 1. Upload the sketch to your ESP32 * 2. Open Serial Monitor (115200 baud) to see connection status * 3. Use DIYables Bluetooth App to connect and view the table * * Tutorial: https://diyables.io/bluetooth-app * Author: DIYables */#include <DIYables_BluetoothServer.h>#include <DIYables_BluetoothTable.h>#include <platforms/DIYables_Esp32Bluetooth.h>// Create Bluetooth instancesDIYables_Esp32Bluetooth bluetooth("ESP32_Table");DIYables_BluetoothServer bluetoothServer(bluetooth);// Create Table app instanceDIYables_BluetoothTable bluetoothTable;// Variables for demo dataunsignedlong lastUpdate = 0;constunsignedlong UPDATE_INTERVAL = 1000; // Update every secondint counter = 0;voidsetup() {Serial.begin(115200);delay(1000);Serial.println("DIYables Bluetooth - ESP32 Table Example");// Initialize Bluetooth server with platform-specific implementation bluetoothServer.begin();// Add table app to server bluetoothServer.addApp(&bluetoothTable);// Define table structure (add rows with attribute names) bluetoothTable.addRow("Temperature"); bluetoothTable.addRow("Humidity"); bluetoothTable.addRow("Pressure"); bluetoothTable.addRow("Counter"); bluetoothTable.addRow("Uptime"); bluetoothTable.addRow("Free Heap"); bluetoothTable.addRow("CPU Freq"); bluetoothTable.addRow("Status");Serial.print("Table rows defined: ");Serial.println(bluetoothTable.getRowCount());// Set up connection event callbacks bluetoothServer.setOnConnected([]() {Serial.println("Bluetooth connected!");// Send table structure bluetoothTable.sendTableStructure();// Send initial values updateTableValues(); }); bluetoothServer.setOnDisconnected([]() {Serial.println("Bluetooth disconnected!"); });// Optional: Handle requests for table data bluetoothTable.onDataRequest([]() {Serial.println("App requested table data"); bluetoothTable.sendTableStructure(); updateTableValues(); });Serial.println("Waiting for Bluetooth connection...");}void updateTableValues() {// TODO: Replace with actual sensor readings// Simulated temperature (20-30°C)float temperature = 20.0 + random(0, 100) / 10.0; bluetoothTable.sendValueUpdate("Temperature", String(temperature, 1) + " °C");// Simulated humidity (40-60%)int humidity = 40 + random(0, 21); bluetoothTable.sendValueUpdate("Humidity", String(humidity) + " %");// Simulated pressure (1000-1020 hPa)int pressure = 1000 + random(0, 21); bluetoothTable.sendValueUpdate("Pressure", String(pressure) + " hPa");// Counter value bluetoothTable.sendValueUpdate("Counter", String(counter)); counter++;// Uptime (in seconds)unsignedlong uptime = millis() / 1000;String uptimeStr = String(uptime / 3600) + "h " + String((uptime % 3600) / 60) + "m " + String(uptime % 60) + "s"; bluetoothTable.sendValueUpdate("Uptime", uptimeStr);// ESP32-specific: Free heap memory bluetoothTable.sendValueUpdate("Free Heap", String(ESP.getFreeHeap()) + " bytes");// ESP32-specific: CPU frequency bluetoothTable.sendValueUpdate("CPU Freq", String(ESP.getCpuFreqMHz()) + " MHz");// Status bluetoothTable.sendValueUpdate("Status", counter % 2 == 0 ? "Running" : "Active");Serial.println("Table values updated");}voidloop() {// Handle Bluetooth server communications bluetoothServer.loop();// Update table values periodically (only when connected)if (bluetooth.isConnected() && millis() - lastUpdate >= UPDATE_INTERVAL) { lastUpdate = millis(); updateTableValues(); }delay(10);}
Nhấp nút Upload trên Arduino IDE để upload code lên ESP32
Mở Serial Monitor
Kiểm tra kết quả trên Serial Monitor. Nó trông như sau:
Newbiely | Arduino IDE 2.3.8
──
☐
✕
File
Edit
Sketch
Tools
Help
ESP32 Dev Module
Newbiely.ino
···
8Serial.println("Hello World!");
Output
Serial Monitor
Message (Enter to send message to 'ESP32 Dev Module' on 'COM15')
New Line
9600 baud
DIYables Bluetooth - ESP32 Table Example
Waiting for Bluetooth connection...
Ln 11, Col 1
ESP32 Dev Module on COM15
2
Code ESP32 BLE (hoạt động với ứng dụng trên cả Android và iOS)
Trên Arduino IDE, vào File Examples DIYables Bluetooth Esp32BLE_Table example, hoặc sao chép code trên và dán vào editor của Arduino IDE
/* * DIYables Bluetooth Library - ESP32 BLE Table Example * Works with DIYables Bluetooth STEM app on Android and iOS * * This example demonstrates the Bluetooth Table feature: * - Display structured data in a two-column table * - Real-time value updates for each row * - Perfect for sensor dashboards and status displays * * Compatible Boards: * - ESP32-WROOM-32 * - ESP32-DevKitC * - ESP32-WROVER * - ESP32-S3 * - ESP32-C3 * - Any ESP32 board supporting BLE * * Note: Select "Huge APP (3MB No OTA/1MB SPIFFS)" partition scheme * in Arduino IDE: Tools > Partition Scheme * * Setup: * 1. Upload the sketch to your ESP32 * 2. Open Serial Monitor (115200 baud) to see connection status * 3. Use DIYables Bluetooth App to connect and view the table * * Tutorial: https://diyables.io/bluetooth-app * Author: DIYables */#include <DIYables_BluetoothServer.h>#include <DIYables_BluetoothTable.h>#include <platforms/DIYables_Esp32BLE.h>// BLE Configurationconst char* DEVICE_NAME = "ESP32BLE_Table";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_Esp32BLE bluetooth(DEVICE_NAME, SERVICE_UUID, TX_UUID, RX_UUID);DIYables_BluetoothServer bluetoothServer(bluetooth);// Create Table app instanceDIYables_BluetoothTable bluetoothTable;// Variables for demo dataunsignedlong lastUpdate = 0;constunsignedlong UPDATE_INTERVAL = 1000;int counter = 0;voidsetup() {Serial.begin(115200);delay(1000);Serial.println("DIYables Bluetooth - ESP32 BLE Table Example");// Initialize Bluetooth server with platform-specific implementation bluetoothServer.begin();// Add table app to server bluetoothServer.addApp(&bluetoothTable);// Define table structure bluetoothTable.addRow("Temperature"); bluetoothTable.addRow("Humidity"); bluetoothTable.addRow("Pressure"); bluetoothTable.addRow("Counter"); bluetoothTable.addRow("Uptime"); bluetoothTable.addRow("Free Heap"); bluetoothTable.addRow("Status");Serial.print("Table rows defined: ");Serial.println(bluetoothTable.getRowCount());// Set up connection event callbacks bluetoothServer.setOnConnected([]() {Serial.println("Bluetooth connected!"); bluetoothTable.sendTableStructure(); updateTableValues(); }); bluetoothServer.setOnDisconnected([]() {Serial.println("Bluetooth disconnected!"); }); bluetoothTable.onDataRequest([]() {Serial.println("App requested table data"); bluetoothTable.sendTableStructure(); updateTableValues(); });Serial.println("Waiting for Bluetooth connection...");}void updateTableValues() {float temperature = 20.0 + random(0, 100) / 10.0; bluetoothTable.sendValueUpdate("Temperature", String(temperature, 1) + " °C");int humidity = 40 + random(0, 21); bluetoothTable.sendValueUpdate("Humidity", String(humidity) + " %");int pressure = 1000 + random(0, 21); bluetoothTable.sendValueUpdate("Pressure", String(pressure) + " hPa"); bluetoothTable.sendValueUpdate("Counter", String(counter)); counter++;unsignedlong uptime = millis() / 1000;String uptimeStr = String(uptime / 3600) + "h " + String((uptime % 3600) / 60) + "m " + String(uptime % 60) + "s"; bluetoothTable.sendValueUpdate("Uptime", uptimeStr); bluetoothTable.sendValueUpdate("Free Heap", String(ESP.getFreeHeap()) + " bytes"); bluetoothTable.sendValueUpdate("Status", counter % 2 == 0 ? "Running" : "Active");Serial.println("Table values updated");}voidloop() { bluetoothServer.loop();if (bluetooth.isConnected() && millis() - lastUpdate >= UPDATE_INTERVAL) { lastUpdate = millis(); updateTableValues(); }delay(10);}
Nhấp nút Upload trên Arduino IDE để upload code lên ESP32
Mở Serial Monitor
Kiểm tra kết quả trên Serial Monitor. Nó trông như sau:
Newbiely | Arduino IDE 2.3.8
──
☐
✕
File
Edit
Sketch
Tools
Help
ESP32 Dev Module
Newbiely.ino
···
8Serial.println("Hello World!");
Output
Serial Monitor
Message (Enter to send message to 'ESP32 Dev Module' on 'COM15')
New Line
9600 baud
DIYables Bluetooth - ESP32 BLE Table Example
Waiting for Bluetooth connection...
Ln 11, Col 1
ESP32 Dev Module on COM15
2
Ứng dụng điện thoại
Cài đặt ứng dụng DIYables Bluetooth trên smartphone của bạn: Android | iOS
Nếu bạn đang sử dụng code ESP32 Classic Bluetooth, bạn cần ghép nối ESP32 với điện thoại Android trước khi mở ứng dụng:
Vào Settings > Bluetooth của điện thoại
Đảm bảo Bluetooth được bật
Điện thoại sẽ quét các thiết bị có sẵn
Tìm và nhấn "ESP32_Table" trong danh sách thiết bị có sẵn
Xác nhận yêu cầu ghép nối (không cần PIN)
Đợi cho đến khi hiển thị "Paired" dưới tên thiết bị
Nếu bạn đang sử dụng code ESP32 BLE, không cần ghép nối. Chỉ cần tiến hành bước tiếp theo.
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 trở xuống) - yêu cầu bởi 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
Trên màn hình chính, nhấn nút Connect. Ứng dụng sẽ quét cả thiết bị BLE và Classic Bluetooth.
Tìm và nhấn thiết bị của bạn trong kết quả quét để kết nối:
Đối với Classic Bluetooth: nhấn "ESP32_Table"
Đối với BLE: nhấn "ESP32BLE_Table"
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 Table từ menu ứng dụng.
Lưu ý: Bạn có thể nhấn 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, xem Hướng dẫn sử dụng DIYables Bluetooth App.
Bảng sẽ được điền với các tên thuộc tính và giá trị hiện tại của chúng
Bây giờ hãy nhìn lại Serial Monitor trên Arduino IDE. Bạn sẽ thấy:
Newbiely | Arduino IDE 2.3.8
──
☐
✕
File
Edit
Sketch
Tools
Help
ESP32 Dev Module
Newbiely.ino
···
8Serial.println("Hello World!");
Output
Serial Monitor
Message (Enter to send message to 'ESP32 Dev Module' on 'COM15')
New Line
9600 baud
Bluetooth connected!
App requested table data
Sent table structure
Temperature: 25.3
Humidity: 62%
Pressure: 1013 hPa
Counter: 1
Uptime: 0h 0m 5s
Free Heap: 245780
Status: Running
Ln 11, Col 1
ESP32 Dev Module on COM15
2
Theo dõi các giá trị bảng cập nhật theo thời gian thực trong ứng dụng
Tùy chỉnh Sáng tạo - Điều chỉnh Code cho Dự án của Bạn
Định nghĩa Hàng Bảng
Thêm các hàng thuộc tính vào bảng (tối đa 20 hàng):
// Thêm hàng trong quá trình setupbluetoothTable.addRow("Temperature");bluetoothTable.addRow("Humidity");bluetoothTable.addRow("Pressure");bluetoothTable.addRow("Status");bluetoothTable.addRow("Uptime");// Kiểm tra số lượng hàngint rows = bluetoothTable.getRowCount();Serial.println("Total rows: " + String(rows));// Lấy tên thuộc tính theo chỉ sốString attr = bluetoothTable.getAttribute(0); // Trả về "Temperature"
Cập nhật Giá trị Hàng
Cập nhật giá trị hàng riêng lẻ theo tên thuộc tính hoặc chỉ số:
// Cập nhật theo tên thuộc tínhbluetoothTable.sendValueUpdate("Temperature", "25.3 °C");bluetoothTable.sendValueUpdate("Humidity", "62%");bluetoothTable.sendValueUpdate("Status", "Running");// Cập nhật theo chỉ số hàng (bắt đầu từ 0)bluetoothTable.sendValueUpdate(0, "25.3 °C"); // Hàng đầu tiênbluetoothTable.sendValueUpdate(1, "62%"); // Hàng thứ hai
Xử lý Yêu cầu Dữ liệu từ Ứng dụng
Khi ứng dụng kết nối hoặc yêu cầu làm mới:
bluetoothTable.onDataRequest([]() {Serial.println("App requested table data"); bluetoothTable.sendTableStructure(); // Gửi tên hàng// Gửi giá trị hiện tại cho tất cả hàng bluetoothTable.sendValueUpdate("Temperature", String(temperature, 1) + " °C"); bluetoothTable.sendValueUpdate("Humidity", String(humidity) + "%"); bluetoothTable.sendValueUpdate("Status", "Online");});
Xóa và Xây dựng lại Bảng
// Xóa tất cả hàngbluetoothTable.clearTable();// Thêm hàng mớibluetoothTable.addRow("Sensor A");bluetoothTable.addRow("Sensor B");// Gửi cấu trúc cập nhật đến ứng dụngbluetoothTable.sendTableStructure();