아두이노 우노 R4 WiFi 블루투스 채팅 예제 BLE를 통한 양방향 메시지 튜토리얼

개요

블루투스 채팅 예제는 DIYables 블루투스 STEM 앱을 통해 접근할 수 있는 양방향 텍스트 메시지 인터페이스를 제공합니다. BLE(Bluetooth Low Energy) 를 사용하는 Arduino UNO R4 WiFi 전용으로 설계되어 Arduino와 스마트폰 사이에서 실시간으로 텍스트 메시지를 주고받을 수 있습니다. 명령줄 인터페이스, 텍스트 명령을 통한 원격 제어, 시리얼 브리지, 대화형 디버깅에 적합합니다.

참고: Arduino UNO R4 WiFi는 BLE(Bluetooth Low Energy)만 지원합니다. 클래식 블루투스는 지원하지 않습니다. DIYables 블루투스 앱은 Android에서 BLE와 클래식 블루투스를 모두 지원하고, iOS에서는 BLE를 지원합니다. 이 보드는 BLE를 사용하므로 앱은 Android와 iOS 모두에서 작동합니다.

아두이노 우노 R4 와이파이 블루투스 채팅 예제 - BLE를 통한 양방향 메시지 튜토리얼

기능

  • 양방향 메시지: 실시간으로 텍스트 메시지 송수신
  • 명령 처리: 모바일 앱에서 입력한 텍스트 명령 처리
  • 시리얼 브리지: 시리얼 모니터와 블루투스 간 메시지 전달
  • 사용자 지정 응답: 에코 또는 처리된 데이터로 자동 응답
  • Android 및 iOS에서 작동: BLE는 두 플랫폼 모두에서 지원
  • 페어링 불필요: BLE는 수동 페어링 없이 자동 연결
  • 저전력: BLE는 클래식 블루투스보다 전력 소비가 적음

필요한 하드웨어

1×아두이노 우노 R4 와이파이 쿠팡 | 아마존
1×(또는) DIYables STEM V4 IoT 쿠팡 | 아마존
1×USB 케이블 타입-A to 타입-C (USB-A PC용) 쿠팡 | 아마존
1×USB 케이블 타입-C to 타입-C (USB-C PC용) 아마존
1×(추천) 아두이노 우노 R4용 스크루 터미널 블록 쉴드 쿠팡 | 아마존
1×(추천) Sensors/Servo Expansion Shield for Arduino UNO R4 아마존
1×(추천) 아두이노 우노 R4용 브레드보드 쉴드 쿠팡 | 아마존
1×(추천) 아두이노 우노 R4용 케이스 쿠팡 | 아마존
1×(추천) 아두이노 우노 R4용 전원 분배기 쿠팡 | 아마존
1×(추천) 아두이노 우노용 프로토타이핑 베이스 플레이트 & 브레드보드 키트 아마존
공개: 이 포스팅 에 제공된 일부 링크는 아마존 제휴 링크입니다. 이 포스팅은 쿠팡 파트너스 활동의 일환으로, 이에 따른 일정액의 수수료를 제공받습니다.
Arduino Uno R4 WiFi Compatible Boards

Arduino UNO R4 WiFi 코드

빠른 단계

다음 단계를 순서대로 따라하세요:

  • Arduino UNO R4 WiFi를 처음 사용하는 경우 아두이노 우노 R4 - 소프트웨어 설치를 참조하세요.
  • USB 케이블을 사용하여 Arduino UNO R4 WiFi 보드를 컴퓨터에 연결합니다.
  • 컴퓨터에서 Arduino IDE를 실행합니다.
  • Arduino UNO R4 WiFi 보드와 적절한 COM 포트를 선택합니다.
  • Arduino IDE 왼쪽 바에서 Libraries 아이콘으로 이동합니다.
  • "DIYables Bluetooth"를 검색한 다음 DIYables의 DIYables Bluetooth 라이브러리를 찾습니다.
  • Install 버튼을 클릭하여 라이브러리를 설치합니다.
아두이노 우노 R4 diyaBLEs 블루투스 라이브러리
  • 다른 라이브러리 종속성 설치를 요청받습니다.
  • Install All 버튼을 클릭하여 모든 라이브러리 종속성을 설치합니다.
아두이노 우노 R4 diyaBLEs 블루투스 종속성

BLE 코드

  • Arduino IDE에서 File Examples DIYables Bluetooth ArduinoBLE_Chat 예제로 이동하거나, 위의 코드를 복사하여 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); }
  • Arduino IDE에서 Upload 버튼을 클릭하여 코드를 Arduino UNO R4 WiFi에 업로드합니다.
  • 시리얼 모니터를 엽니다.
  • 시리얼 모니터에서 결과를 확인합니다. 아래와 같이 표시됩니다:
Newbiely | Arduino IDE 2.3.8
──
File
Edit
Sketch
Tools
Help
Arduino Uno R4 WiFi
Newbiely.ino
···
8 Serial.println("Hello World!");
Output
Serial Monitor
Message (Enter to send message to 'Arduino Uno R4 WiFi' on 'COM15')
New Line
9600 baud
DIYables Bluetooth - Chat Example Waiting for Bluetooth connection...
Ln 11, Col 1
Arduino Uno R4 WiFi on COM15
2

모바일 앱

  • 스마트폰에 DIYables 블루투스 앱을 설치하세요: Android | iOS

참고: DIYables 블루투스 앱은 Android에서 BLE와 클래식 블루투스를 모두 지원하고, iOS에서는 BLE를 지원합니다. Arduino UNO R4 WiFi는 BLE를 사용하므로 앱은 Android와 iOS 모두에서 작동합니다. BLE에는 수동 페어링이 필요 없으며 스캔하고 연결하기만 하면 됩니다.

  • DIYables 블루투스 앱을 엽니다.
  • 처음 앱을 열면 권한을 요청합니다. 다음을 허용해 주세요:
    • 주변 기기(Nearby Devices) 권한(Android 12+) / 블루투스 권한(iOS) - 블루투스 기기를 스캔하고 연결하는 데 필요합니다.
    • 위치(Location) 권한(Android 11 이하만 해당) - 구형 Android 버전에서 BLE 기기를 스캔하는 데 필요합니다.
  • 휴대폰에서 블루투스가 켜져 있는지 확인합니다.
  • 홈 화면에서 Connect 버튼을 탭합니다. 앱이 BLE 기기를 스캔합니다.
diyaBLEs 블루투스 앱 - 스캔 버튼이 있는 홈 화면
  • 스캔 결과에서 "Arduino_Chat"을 찾아 탭하여 연결합니다.
  • 연결되면 앱이 자동으로 홈 화면으로 돌아갑니다. 앱 메뉴에서 채팅 앱을 선택합니다.
diyaBLEs 블루투스 앱 - 채팅 앱이 있는 홈 화면

참고: 홈 화면의 설정 아이콘을 탭하면 앱을 표시하거나 숨길 수 있습니다. 자세한 내용은 DIYables 블루투스 앱 사용 설명서를 참조하세요.

  • 채팅 입력란에 메시지를 입력하고 전송을 탭합니다.
diyaBLEs 블루투스 앱 - 채팅 화면

이제 Arduino IDE의 시리얼 모니터를 다시 확인하세요. 다음과 같이 표시됩니다:

Newbiely | Arduino IDE 2.3.8
──
File
Edit
Sketch
Tools
Help
Arduino Uno R4 WiFi
Newbiely.ino
···
8 Serial.println("Hello World!");
Output
Serial Monitor
Message (Enter to send message to 'Arduino Uno R4 WiFi' on 'COM15')
New Line
9600 baud
Bluetooth connected! Received: Hello
Ln 11, Col 1
Arduino Uno R4 WiFi on COM15
2
  • Arduino가 메시지를 에코로 돌려보내며, 앱 채팅에서 응답을 확인할 수 있습니다.

창의적인 커스터마이징 - 프로젝트에 맞게 코드 적용하기

채팅 메시지 처리

onChatMessage() 콜백을 사용하여 앱에서 입력한 메시지를 받고 처리합니다. 프로젝트에 맞는 사용자 지정 명령어를 정의할 수 있으며, Arduino는 그에 따라 반응합니다:

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

더 많은 else if 블록을 추가하여 원하는 만큼 사용자 지정 명령어를 추가할 수 있습니다. 예를 들어, 핀을 제어하려면 LED_ON / LED_OFF를, 센서 값을 읽으려면 READ를 추가하면 됩니다. 앱에서 입력하는 모든 단어가 명령어가 됩니다.

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

시리얼-블루투스 브리지

시리얼 모니터와 블루투스 간 메시지를 전달합니다:

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

연결 이벤트 처리

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

채팅 사용 방법

앱 인터페이스

DIYables 블루투스 앱의 채팅 인터페이스는 다음을 제공합니다:

  • 메시지 목록: 타임스탬프가 포함된 송수신 메시지 표시
  • 텍스트 입력: Arduino로 전송할 메시지 입력
  • 전송 버튼: 탭하여 메시지 전송

통신 흐름

  1. 앱에서 메시지를 입력하면 Arduino가 onChatMessage() 콜백으로 수신합니다.
  2. Arduino가 메시지를 처리하고 필요에 따라 bluetoothChat.send()로 응답을 전송합니다.
  3. 응답이 앱 채팅 창에 표시됩니다.

프로그래밍 예제

릴레이 제어 명령 처리기

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

센서 조회 시스템

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

주기적인 상태 업데이트

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

고급 프로그래밍 기법

다중 단어 명령 파싱

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

타임스탬프가 있는 채팅 로거

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

문제 해결

일반적인 문제

1. 앱에서 기기를 찾을 수 없음

  • Arduino UNO R4 WiFi가 전원이 켜져 있고 스케치가 업로드되어 있는지 확인하세요.
  • 휴대폰의 블루투스가 활성화되어 있는지 확인하세요.
  • Android 11 이하에서는 위치 서비스도 활성화하세요.
  • 휴대폰의 블루투스를 재시작해 보세요.

2. Arduino가 메시지를 수신하지 못함

  • 앱에서 블루투스 연결 상태를 확인하세요.
  • onChatMessage 콜백이 올바르게 설정되어 있는지 확인하세요.
  • 시리얼 모니터에서 오류 메시지를 확인하세요.

3. Arduino 응답이 앱에 표시되지 않음

  • bluetoothChat.send()가 호출되고 있는지 확인하세요.
  • bluetoothServer.loop()가 메인 루프에서 호출되고 있는지 확인하세요.
  • bluetooth.isConnected()로 연결이 활성 상태인지 확인하세요.

4. 시리얼 모니터에 깨진 텍스트 표시

  • 시리얼 모니터의 보드레이트가 Serial.begin(9600)과 일치하는지 확인하세요.
  • Arduino IDE에서 올바른 보드가 선택되어 있는지 확인하세요.

5. 연결이 자주 끊김

  • Arduino와 더 가까이 이동하세요(거리 줄이기).
  • 다른 BLE 기기로 인한 간섭을 확인하세요.
  • 안정적인 USB 전원 공급을 확인하세요.

6. 업로드 실패 또는 보드를 인식하지 못함

  • 보드 관리자를 통해 최신 Arduino UNO R4 보드 패키지를 설치하세요.
  • 다른 USB 케이블이나 포트를 사용해 보세요.
  • 업로드 전에 보드의 리셋 버튼을 눌러보세요.

프로젝트 아이디어

통신

  • 홈 자동화를 위한 텍스트 명령 인터페이스
  • 무선 디버깅을 위한 시리얼-블루투스 브리지
  • 원격 센서 조회 시스템
  • 대화형 퀴즈 또는 트리비아 게임

제어 시스템

  • 음성-텍스트 릴레이 제어
  • 다중 기기 명령 라우터
  • 채팅 명령을 통한 설정 관리자
  • 펌웨어 버전 보고기

로깅 및 모니터링

  • 타임스탬프가 있는 이벤트 로거
  • 알람 알림 시스템
  • 상태 보고서 생성기
  • 진단 채팅 봇

다른 블루투스 앱과의 통합

블루투스 모니터와 결합

채팅은 명령에, 모니터는 지속적인 출력에 사용합니다:

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

블루투스 테이블과 결합

채팅 명령으로 테이블에 표시되는 데이터를 제어합니다:

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

다음 단계

블루투스 채팅 예제를 마스터한 후 다음을 시도해 보세요:

  1. 블루투스 모니터 - 단방향 상태 스트리밍용
  2. 블루투스 슬라이더 - 아날로그 값 제어용
  3. 블루투스 테이블 - 구조화된 데이터 표시용
  4. 다중 블루투스 앱 - 채팅과 다른 앱 결합

지원

추가 도움이 필요하면:

  • API 레퍼런스 문서를 확인하세요.
  • DIYables 튜토리얼을 방문하세요.
  • Arduino 커뮤니티 포럼