블루투스 채팅 예제는 DIYables Bluetooth STEM 앱을 통해 ESP32와 스마트폰 간에 양방향 텍스트 메시지를 가능하게 합니다. ESP32 보드용으로 설계되었으며 BLE(블루투스 저에너지)와 클래식 블루투스 연결을 모두 지원합니다. 실시간으로 텍스트 메시지를 주고받고, 커스텀 명령 처리를 구현하고, 시리얼 모니터를 블루투스에 브리지하세요 — 디버깅, 원격 제어, 인터랙티브 프로젝트에 적합합니다.
이 예제는 두 가지 블루투스 모드를 지원합니다:
ESP32 BLE (블루투스 저에너지): Android와 iOS 모두에서 작동
ESP32 클래식 블루투스: Android에서만 작동. iOS는 클래식 블루투스를 지원하지 않습니다. iOS 지원이 필요한 경우 BLE를 사용하세요.
기능
양방향 메시지: 실시간으로 텍스트 메시지 주고받기
에코 모드: 수신된 메시지를 자동으로 앱에 다시 에코
명령 처리: 커스텀 텍스트 명령 처리(ping, status, time, heap)
주기적 메시지: 설정 가능한 간격으로 자동 상태 업데이트 전송
Serial-Bluetooth 브리지: 시리얼 모니터에 메시지를 입력하여 앱으로 전송
BLE & 클래식 블루투스: 프로젝트에 맞는 블루투스 모드 선택
크로스 플랫폼: BLE 모드는 Android와 iOS 모두에서 작동; 클래식 블루투스는 Android에서만 작동
"DIYables Bluetooth"를 검색한 다음 DIYables의 DIYables Bluetooth 라이브러리를 찾습니다.
설치 버튼을 클릭하여 라이브러리를 설치합니다.
다른 라이브러리 종속성 설치 여부를 묻는 메시지가 표시됩니다.
모두 설치 버튼을 클릭하여 모든 라이브러리 종속성을 설치합니다.
필요에 따라 아래 두 가지 블루투스 모드 중 하나를 선택하세요:
ESP32 클래식 블루투스 코드 (Android의 앱에서만 작동)
참고: 클래식 블루투스는 iOS에서 지원되지 않습니다. iOS 지원이 필요한 경우 아래 BLE 코드를 사용하세요.
Arduino IDE에서 파일 예제 DIYables Bluetooth Esp32Bluetooth_Chat 예제로 이동하거나, 위의 코드를 복사하여 Arduino IDE 편집기에 붙여넣습니다.
/* * DIYables Bluetooth Library - ESP32 Classic Bluetooth Chat 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 Chat feature: * - Two-way text messaging via Bluetooth * - Receive messages from mobile app * - Send messages to mobile app * * 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 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_Esp32Bluetooth.h>// Create Bluetooth instancesDIYables_Esp32Bluetooth bluetooth("ESP32_Chat");DIYables_BluetoothServer bluetoothServer(bluetooth);// Create Chat app instanceDIYables_BluetoothChat bluetoothChat;// Variables for periodic messagesunsignedlong lastMessageTime = 0;constunsignedlong MESSAGE_INTERVAL = 10000; // Send message every 10 secondsint messageCount = 0;voidsetup() {Serial.begin(115200);delay(1000);Serial.println("DIYables Bluetooth - ESP32 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! ESP32 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 backString response = "Echo: "; response += message; bluetoothChat.send(response);// You can add custom command handling hereif (message.equalsIgnoreCase("ping")) { bluetoothChat.send("pong!"); } elseif (message.equalsIgnoreCase("status")) { bluetoothChat.send("ESP32 is running normally"); } elseif (message.equalsIgnoreCase("time")) {String timeMsg = "Uptime: "; timeMsg += String(millis() / 1000); timeMsg += " seconds"; bluetoothChat.send(timeMsg); } elseif (message.equalsIgnoreCase("heap")) {String heapMsg = "Free heap: "; heapMsg += String(ESP.getFreeHeap()); heapMsg += " bytes"; bluetoothChat.send(heapMsg); } });Serial.println("Waiting for Bluetooth connection..."); Serial.println("Type 'ping', 'status', 'time', or'heap' 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 Bluetoothif (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);}
Arduino IDE에서 업로드 버튼을 클릭하여 ESP32에 코드를 업로드합니다.
시리얼 모니터를 엽니다.
시리얼 모니터에서 결과를 확인합니다. 다음과 같이 표시됩니다:
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 Chat Example
Waiting for Bluetooth connection...
Type 'ping', 'status', 'time', or 'heap' in the app to test commands
Ln 11, Col 1
ESP32 Dev Module on COM15
2
ESP32 BLE 코드 (Android과 iOS 앱 모두에서 작동)
Arduino IDE에서 파일 예제 DIYables Bluetooth Esp32BLE_Chat 예제로 이동하거나, 위의 코드를 복사하여 Arduino IDE 편집기에 붙여넣습니다.
/* * DIYables Bluetooth Library - ESP32 BLE 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: * - 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 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_Esp32BLE.h>// BLE Configurationconst char* DEVICE_NAME = "ESP32BLE_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 instancesDIYables_Esp32BLE bluetooth(DEVICE_NAME, SERVICE_UUID, TX_UUID, RX_UUID);DIYables_BluetoothServer bluetoothServer(bluetooth);// Create Chat app instanceDIYables_BluetoothChat bluetoothChat;// Variables for periodic messagesunsignedlong lastMessageTime = 0;constunsignedlong MESSAGE_INTERVAL = 10000; // Send message every 10 secondsint messageCount = 0;voidsetup() {Serial.begin(115200);delay(1000);Serial.println("DIYables Bluetooth - ESP32 BLE 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! ESP32 BLE 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 backString response = "Echo: "; response += message; bluetoothChat.send(response);// Custom command handlingif (message.equalsIgnoreCase("ping")) { bluetoothChat.send("pong!"); } elseif (message.equalsIgnoreCase("status")) { bluetoothChat.send("ESP32 BLE is running normally"); } elseif (message.equalsIgnoreCase("time")) {String timeMsg = "Uptime: "; timeMsg += String(millis() / 1000); timeMsg += " seconds"; bluetoothChat.send(timeMsg); } elseif (message.equalsIgnoreCase("heap")) {String heapMsg = "Free heap: "; heapMsg += String(ESP.getFreeHeap()); heapMsg += " bytes"; bluetoothChat.send(heapMsg); } });Serial.println("Waiting for Bluetooth connection..."); Serial.println("Type 'ping', 'status', 'time', or'heap' in the app to test commands");}void loop() { bluetoothServer.loop(); 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); } 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);}
Arduino IDE에서 업로드 버튼을 클릭하여 ESP32에 코드를 업로드합니다.
시리얼 모니터를 엽니다.
시리얼 모니터에서 결과를 확인합니다. 다음과 같이 표시됩니다:
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 Chat Example
Waiting for Bluetooth connection...
Type 'ping', 'status', 'time', or 'heap' in the app to test commands
// Send a simple text messagebluetoothChat.send("Hello from ESP32!");// Send sensor data as textfloat temperature = 25.3;bluetoothChat.send("Temperature: " + String(temperature) + "°C");// Send status updatesbluetoothChat.send("System ready");
연결 이벤트 처리
// Called when the app connects to ESP32bluetoothServer.setOnConnected([]() {Serial.println("Bluetooth connected!"); bluetoothChat.send("Welcome! ESP32 is ready to chat.");});// Called when the app disconnects from ESP32bluetoothServer.setOnDisconnected([]() {Serial.println("Bluetooth disconnected!");});// Check connection status anywhere in your codeif (bluetoothServer.isConnected()) { bluetoothChat.send("Still connected!");}
Serial-Bluetooth 브리지
Arduino IDE 시리얼 모니터에서 입력한 메시지를 블루투스 앱으로 전달합니다:
voidloop() { bluetoothServer.loop();// Read from Serial and send to Bluetoothif (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);}