DIYables ESP32 WebApps 라이브러리를 사용한 아두이노 나노 ESP32 웹 채팅

개요

이 튜토리얼은 Arduino Nano ESP32에서 DIYables ESP32 WebApps 라이브러리의 DIYablesWebChatPage 클래스를 사용하는 방법을 보여줍니다. 보드는 WebSocket 서버를 실행하고, 브라우저가 연결하여 실시간으로 일반 텍스트 메시지를 교환합니다. 스케치는 수신 메시지를 파싱하고 텍스트, LED 제어 또는 다른 작업으로 응답할 수 있습니다.

아두이노 나노 ESP32 웹 채팅

DIYables ESP32 WebApps 앱으로 WebChat을 사용하는 방법을 보여주는 단계별 영상 튜토리얼:

이 튜토리얼에서 다루는 내용

  • WebSocket을 통해 Arduino Nano ESP32 채팅 인터페이스에 브라우저 연결하기
  • 수신 채팅 메시지 파싱 및 스케치에서 응답 생성하기
  • 입력된 명령을 통해 내장 LED 제어하기
  • 같은 WiFi 네트워크의 스마트폰이나 PC에서 채팅 페이지 액세스하기

준비물

1×아두이노 나노 ESP32 쿠팡 | 아마존
1×USB 케이블 타입-A to 타입-C (USB-A PC용) 쿠팡 | 아마존
1×USB 케이블 타입-C to 타입-C (USB-C PC용) 아마존
1×(추천) 아두이노 나노용 스크루 터미널 확장 보드 쿠팡 | 아마존
1×(추천) 아두이노 나노용 브레이크아웃 확장 보드 쿠팡 | 아마존
1×(추천) 아두이노 나노 ESP32용 전원 분배기 쿠팡 | 아마존
공개: 이 포스팅 에 제공된 일부 링크는 아마존 제휴 링크입니다. 이 포스팅은 쿠팡 파트너스 활동의 일환으로, 이에 따른 일정액의 수수료를 제공받습니다.

설정 지침

단계

다음 지침을 단계별로 따르세요:

  • Arduino Nano ESP32가 처음이라면, 아두이노 나노 ESP32 - 소프트웨어 설치 튜토리얼을 참조하세요.
  • USB 케이블을 사용하여 Arduino Nano ESP32 보드를 컴퓨터에 연결합니다.
  • 컴퓨터에서 Arduino IDE를 실행합니다.
  • 적절한 보드(예: Arduino Nano ESP32)와 COM 포트를 선택합니다.
  • Arduino IDE 왼쪽 바의 Libraries 아이콘으로 이동합니다.
  • "DIYables ESP32 WebApps"를 검색하여 DIYables의 DIYables ESP32 WebApps 라이브러리를 찾습니다
  • Install 버튼을 클릭하여 라이브러리를 설치합니다.
  • Search for DIYables ESP32 WebApps created by DIYables and click the Install button.
Newbiely | Arduino IDE 2.3.8
──
File
Edit
Sketch
Tools
Help
Arduino Nano ESP32
Library Manager
Type:
All
Topic:
All
DIYables ESP32 WebApps by DIYables
A comprehensive library designed for ESP32 that provides multiple professional web applications including Web Monitor, Chat, Digital Pin Control, Sliders, Joystick, Analog Gauge, Rotator Control, and Temperature Display via WebSocket communication. Features modular architecture for memory efficiency, automatic config handling, and perfect for IoT projects, robotics, sensor monitoring, servo/stepper control, temperature monitoring, and remote ESP32 control. More info
1.0.1
INSTALL
Newbiely.ino
···
1 void setup() {
Output
Serial Monitor
Ln 1, Col 1
Arduino Nano ESP32 on COM15
1
  • 다른 라이브러리 의존성 설치 요청을 받게 됩니다
  • Install All 버튼을 클릭하여 모든 라이브러리 의존성을 설치합니다.
  • Arduino IDE에서 File Examples DIYables ESP32 WebApps WebChat 예제로 이동하거나, 위의 코드를 복사하여 Arduino IDE 편집기에 붙여넣습니다
/* * DIYables WebApp Library - WebChat Example * * This example demonstrates the WebChat feature: * - Interactive chat interface * - Intelligent ESP32 responses * - Built-in LED control via chat commands * * Hardware: ESP32 Boards * * Setup: * 1. Update WiFi credentials below * 2. Upload the sketch to your Arduino * 3. Open Serial Monitor to see the IP address * 4. Navigate to http://[IP_ADDRESS]/chat */ #include <DIYables_ESP32_Platform.h> #include <DIYablesWebApps.h> // WiFi credentials - UPDATE THESE WITH YOUR NETWORK const char WIFI_SSID[] = "YOUR_WIFI_SSID"; const char WIFI_PASSWORD[] = "YOUR_WIFI_PASSWORD"; // Create WebApp server and page instances ESP32ServerFactory serverFactory; DIYablesWebAppServer webAppsServer(serverFactory, 80, 81); DIYablesHomePage homePage; DIYablesWebChatPage chatPage; // Chat variables String userName = ""; int chatCount = 0; void setup() { Serial.begin(9600); delay(1000); Serial.println("DIYables ESP32 WebApp - WebChat Example"); // Add only home and webchat pages webAppsServer.addApp(&homePage); webAppsServer.addApp(&chatPage); // Optional: Add 404 page for better user experience (local object) webAppsServer.setNotFoundPage(DIYablesNotFoundPage()); // Initialize LED for chat commands pinMode(LED_BUILTIN, OUTPUT); // Start the WebApp server if (!webAppsServer.begin(WIFI_SSID, WIFI_PASSWORD)) { while (1) { Serial.println("Failed to start WebApp server!"); delay(1000); } } // Set up chat callback chatPage.onChatMessage([](const String& message) { chatCount++; Serial.println("Chat message #" + String(chatCount) + ": " + message); String response = ""; String lowerMessage = message; lowerMessage.toLowerCase(); // Process chat commands if (lowerMessage.indexOf("hello") >= 0 || lowerMessage.indexOf("hi") >= 0) { response = "Hello! I'm your ESP32 assistant. Try saying 'led on' or 'led off' to control the LED!"; chatPage.sendToChat(response); return; } if (lowerMessage.indexOf("led on") >= 0 || lowerMessage.indexOf("light on") >= 0) { digitalWrite(LED_BUILTIN, HIGH); response = "LED is now ON! ✨"; chatPage.sendToChat(response); return; } if (lowerMessage.indexOf("led off") >= 0 || lowerMessage.indexOf("light off") >= 0) { digitalWrite(LED_BUILTIN, LOW); response = "LED is now OFF! 💡"; chatPage.sendToChat(response); return; } if (lowerMessage.indexOf("status") >= 0) { String ledStatus = digitalRead(LED_BUILTIN) ? "ON" : "OFF"; response = "Arduino Status: LED is " + ledStatus + ", Uptime: " + String(millis() / 1000) + " seconds"; chatPage.sendToChat(response); return; } if (lowerMessage.indexOf("help") >= 0) { response = "Available commands: 'led on', 'led off', 'status', 'help'. Just chat with me!"; chatPage.sendToChat(response); return; } if (lowerMessage.indexOf("time") >= 0) { response = "Arduino has been running for " + String(millis() / 1000) + " seconds."; chatPage.sendToChat(response); return; } if (lowerMessage.indexOf("name") >= 0) { response = "I'm your ESP32! What's your name?"; chatPage.sendToChat(response); return; } // General responses String responses[] = { "That's interesting! Tell me more.", "I understand! As an Arduino, I love processing your messages.", "Cool! I'm here and ready to help.", "Thanks for chatting with me! Try 'led on' to see something happen.", "I'm just an Arduino, but I enjoy our conversation!" }; response = responses[chatCount % 5]; chatPage.sendToChat(response); }); // Send welcome message chatPage.sendToChat("Arduino Chat Bot is online! 🤖"); chatPage.sendToChat("Say 'hello' or 'help' to get started!"); } void loop() { // Handle WebApp server communications webAppsServer.loop(); // Add your main application code here delay(10); }
  • 스케치의 WiFi 자격 증명을 업데이트합니다:
const char WIFI_SSID[] = "YOUR_WIFI_NETWORK"; const char WIFI_PASSWORD[] = "YOUR_WIFI_PASSWORD";
  • Arduino IDE의 Upload 버튼을 클릭하여 코드를 Arduino Nano ESP32에 업로드합니다
  • 시리얼 모니터를 엽니다
  • 시리얼 모니터 출력은 다음과 유사해야 합니다:
Newbiely | Arduino IDE 2.3.8
──
File
Edit
Sketch
Tools
Help
Arduino Nano ESP32
Newbiely.ino
···
8 Serial.println("Hello World!");
Output
Serial Monitor
Message (Enter to send message to 'Arduino Nano ESP32' on 'COM15')
New Line
9600 baud
DIYables WebApp - WebChat Example INFO: Added app / INFO: Added app /chat DIYables WebApp Library Platform: Arduino Nano ESP32 Network connected! IP address: 192.168.0.2 HTTP server started on port 80 Configuring WebSocket server callbacks... WebSocket server started on port 81 WebSocket URL: ws://192.168.0.2:81 WebSocket server started on port 81 ========================================== DIYables WebApp Ready! ========================================== Web Interface: http://192.168.0.2 WebSocket: ws://192.168.0.2:81 Available Applications: Home Page: http://192.168.0.2/ WebChat: http://192.168.0.2/chat ==========================================
Ln 11, Col 1
Arduino Nano ESP32 on COM15
2
  • 아무것도 표시되지 않으면 보드의 리셋 버튼을 누릅니다.
  • 출력에 표시된 IP 주소를 기록하고 같은 네트워크에 연결된 스마트폰이나 PC의 브라우저에 입력합니다.
  • 예시: http://192.168.0.2
  • 홈 페이지에는 등록된 애플리케이션의 링크가 표시됩니다:
아두이노 나노 ESP32 diyaBLEs webapp 홈 페이지 - 웹 채팅 앱 포함
  • Chat 링크를 선택하여 채팅 인터페이스를 엽니다:
아두이노 나노 ESP32 diyaBLEs webapp 웹 채팅 앱
  • 페이지는 http://192.168.0.2/chat에서 직접 액세스할 수도 있습니다.

지원되는 명령

예제 스케치는 다음 채팅 입력을 인식합니다:

LED 제어

  • led on 또는 turn on led — 내장 LED를 켭니다
  • led off 또는 turn off led — 내장 LED를 끕니다
  • blink 또는 blink led — LED를 깜박입니다

상태 및 정보

  • hello 또는 hi — 인사 메시지를 반환합니다
  • help — 인식된 명령 목록을 표시합니다
  • time — 보드 가동 시간을 보고합니다
  • status — 시스템 상태를 보고합니다
  • how are you? — 상태 메시지를 반환합니다
  • what can you do? — 기능 목록을 표시합니다
  • what is your name? — 보드 이름을 반환합니다

예제 세션

You: Hello ESP32: Hi there! I'm your assistant. What's your name? You: My name is John ESP32: Nice to meet you, John! I'm ready to help. You: led on ESP32: LED turned ON for you, John! You: what can you do? ESP32: I can control LEDs, respond to your messages, and remember your name. Try saying 'help' for commands! You: help ESP32: Available commands: * 'led on/off' - Control LED * 'blink' - Blink LED * 'status' - Show system info * 'time' - Show uptime

코드 구조

스케치는 세 가지 구성 요소를 중심으로 구성됩니다:

  1. WebApp 서버 — HTTP 라우팅 및 WebSocket 연결을 관리합니다
  2. 채팅 페이지/chat 경로를 등록하고 브라우저 UI를 제공합니다
  3. 메시지 핸들러 — 수신 채팅 메시지마다 호출되는 콜백

메시지 핸들러는 텍스트를 받아 파싱하고 chatPage.sendToWebChat()을 사용하여 응답을 보냅니다.

명령 추가

명령 세트를 확장하려면 메시지 핸들러 콜백 내에 조건을 추가합니다:

// Handle incoming chat messages in the onWebChatMessage callback if (message.indexOf("your_command") >= 0) { response = "Your custom response"; // Execute associated hardware action }

다른 하드웨어 제어

같은 패턴이 모든 주변 장치에 적용됩니다:

// Move a servo when commanded if (message.indexOf("move servo") >= 0) { servo.write(90); response = "Servo moved to 90 degrees"; } // Read a sensor on demand if (message.indexOf("temperature") >= 0) { float temp = readTemperature(); response = "Current temperature: " + String(temp) + " C"; }

문제 해결

보드가 메시지에 응답하지 않는 경우

  • 오류 출력을 위해 시리얼 모니터를 확인합니다
  • 브라우저의 WebSocket 상태 표시기가 "connected"를 표시하는지 확인합니다
  • 페이지를 새로 고침합니다

WiFi 연결 실패

  • SSID와 비밀번호를 확인합니다
  • Arduino Nano ESP32는 2.4 GHz 네트워크에만 연결됩니다; 5 GHz는 지원되지 않습니다
  • 신호가 약한 경우 보드를 라우터에 가깝게 이동합니다

채팅 페이지에 도달할 수 없는 경우

  • 시리얼 모니터에서 IP 주소를 확인합니다
  • 브라우저 장치가 보드와 같은 WiFi 네트워크에 있는지 확인합니다
  • 먼저 홈 페이지(http://[IP]/)를 시도하여 서버가 실행 중인지 확인합니다

LED가 응답하지 않는 경우

  • 예제는 내장 LED를 사용하므로 배선이 필요하지 않습니다
  • 명령 철자가 인식된 문자열과 일치하는지 확인합니다
  • 보드가 수신한 원시 메시지를 위해 시리얼 모니터를 확인합니다