DIYables ESP32 Web Apps Chat

Overview

The WebChat example demonstrates how to create an interactive chat interface between a web browser and Arduino. Designed for ESP32 educational platform with enhanced IoT capabilities and seamless integration with built-in sensors. The ESP32 can respond intelligently to messages and control hardware based on chat commands.

Arduino WebChat Example - Interactive Chat Interface Tutorial

Features

  • Real-time Chat: Instant messaging via WebSocket
  • Intelligent Responses: ESP32 provides contextual replies
  • LED Control: Control built-in LED via chat commands
  • User Recognition: ESP32 remembers your name
  • Message History: View conversation history
  • Responsive Design: Works on desktop and mobile

Hardware Used In This Tutorial

1×ESP-WROOM-32 Dev Module
1×USB Cable Type-A to Type-C (for USB-A PC)
1×USB Cable Type-C to Type-C (for USB-C PC)
1×Recommended: Screw Terminal Expansion Board for ESP32
1×Recommended: Breakout Expansion Board for ESP32
1×Recommended: Power Splitter for ESP32

Or you can buy the following kits:

1×DIYables ESP32 Starter Kit (ESP32 included)
1×DIYables Sensor Kit (30 sensors/displays)
1×DIYables Sensor Kit (18 sensors/displays)
Disclosure: Some of the links in this section are Amazon affiliate links, meaning we may earn a commission at no additional cost to you if you make a purchase through them. Additionally, some links direct you to products from our own brand, DIYables .

Setup Instructions

Quick Instructions

Follow these instructions step by step:

  • If this is your first time using the ESP32, refer to the tutorial on setting up the environment for ESP32 in the Arduino IDE.
  • Connect the ESP32 board to your computer using a USB cable.
  • Launch the Arduino IDE on your computer.
  • Select the appropriate ESP32 board (e.g. ESP32 Dev Module) and COM port.
  • Navigate to the Libraries icon on the left bar of the Arduino IDE.
  • Search "DIYables ESP32 WebApps", then find the DIYables ESP32 WebApps Library by DIYables
  • Click Install button to install the library.
DIYables ESP32 WebApps Library
  • You will be asked for installing some other library dependencies
  • Click Install All button to install all library dependencies.
DIYables ESP32 WebApps dependency
  • On Arduino IDE, Go to File Examples DIYables ESP32 WebApps WebChat example, or copy the above code and paste it to the editor of 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); }
  • Configure WiFi credentials in the code by updating these lines:
const char WIFI_SSID[] = "YOUR_WIFI_NETWORK"; const char WIFI_PASSWORD[] = "YOUR_WIFI_PASSWORD";
  • Click Upload button on Arduino IDE to upload code to ESP32
  • Open the Serial Monitor
  • Check out the result on Serial Monitor. It looks like the below
COM6
Send
DIYables WebApp - WebChat Example INFO: Added app / INFO: Added app /chat DIYables WebApp Library Platform: 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 ==========================================
Autoscroll Show timestamp
Clear output
9600 baud  
Newline  
  • If you do not see anything, reboot ESP32 board.
  • Take note of the IP address displayed, and enter this address into the address bar of a web browser on your smartphone or PC.
  • Example: http://192.168.0.2
  • You will see the home page like below image:
ESP32 DIYables WebApp Home page with Web Chat app
  • Click to the Chat link, you will see the Web Chat app's UI like the below:
ESP32 DIYables WebApp Web Chat app
  • Or you can also access the page directly by IP address followed by /chat. For example: http://192.168.0.2/chat
  • Start chatting with your Arduino! Type your name when prompted and try commands like "led on", "hello", or "help" to interact with your Arduino.

How to Use

Starting a Conversation

  1. Open the chat interface in your browser
  2. Type your name when prompted
  3. Start chatting with your Arduino!

Chat Commands

The ESP32 recognizes these special commands:

LED Control

  • "led on" or "turn on led" → Turns on built-in LED
  • "led off" or "turn off led" → Turns off built-in LED
  • "blink" or "blink led" → Makes LED blink

Information Commands

  • "hello" or "hi" → Friendly greeting
  • "help" → Shows available commands
  • "time" → Shows ESP32 uptime
  • "status" → Shows system status

Questions

  • "how are you?" → ESP32 shares its status
  • "what can you do?" → Lists capabilities
  • "what is your name?" → ESP32 introduces itself

Example Conversation

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

Creative Customization - Build Your Interactive Assistant

Transform this basic chat example into something amazing! The modular design allows you to adapt and expand the functionality to create your own unique interactive ESP32 assistant.

Code Structure

Main Components

  1. WebApp Server: Manages HTTP and WebSocket connections
  2. Chat Page: Provides the web interface
  3. Message Handler: Processes incoming chat messages
  4. Response Generator: Creates intelligent replies

Key Functions

// Handle incoming chat messages void handleChatMessage(String message, String clientId) { // Process message and generate response } // Send message to web interface void sendChatResponse(String response, String clientId) { // Send response via WebSocket }

Adding Custom Commands

To add new chat commands, modify the handleChatMessage function:

if (message.indexOf("your_command") >= 0) { response = "Your custom response"; // Add your custom action here }

Customization Options

Modify ESP32 Personality

Edit the response messages to change Arduino's personality:

String greetings[] = { "Hello! How can I help you today?", "Hi there! Ready to chat?", "Greetings! What's on your mind?" };

Add Hardware Control

Extend LED control to other components:

// Control servo motor if (message.indexOf("move servo") >= 0) { servo.write(90); response = "Servo moved to 90 degrees!"; } // Read sensor data if (message.indexOf("temperature") >= 0) { float temp = getTemperature(); response = "Current temperature: " + String(temp) + "°C"; }

Change Web Interface Theme

The chat interface can be customized by modifying CSS in the library files:

  • Colors: Edit gradient backgrounds
  • Fonts: Change font families
  • Layout: Adjust spacing and sizing

Troubleshooting

Common Issues

1. ESP32 not responding to messages

  • Check Serial Monitor for error messages
  • Verify WebSocket connection status
  • Refresh the browser page

2. WiFi connection failed

  • Double-check SSID and password
  • Ensure 2.4GHz network (not 5GHz)
  • Check signal strength

3. Can't access chat page

  • Verify IP address is correct
  • Check if ESP32 is still connected to WiFi
  • Try accessing home page first: http://[IP]/

4. LED not responding to commands

  • Check wiring (built-in LED should work by default)
  • Verify commands are spelled correctly
  • Check Serial Monitor for debug messages

Debug Tips

Enable debug mode by adding this line in setup():

Serial.println("Debug mode enabled");

Monitor Serial output to see:

  • Incoming messages
  • Command parsing
  • Response generation
  • Hardware actions

Advanced Features

Multiple Client Support

The chat supports multiple users simultaneously:

  • Each user has a unique session
  • ESP32 remembers individual names
  • Broadcast messages to all users

Message Persistence

Add message logging to EEPROM:

#include <EEPROM.h> void saveMessage(String message) { // Save to EEPROM for persistence }

Integration with Sensors

Connect sensors and make them accessible via chat:

// Temperature sensor if (message.indexOf("temperature") >= 0) { float temp = analogRead(A0) * 0.1; // Example conversion response = "Temperature: " + String(temp) + "°C"; }

Next Steps

After mastering the Chat example, try:

  1. WebMonitor - For debugging and development
  2. DigitalPins - For controlling multiple outputs
  3. Joystick - For directional control
  4. MultipleWebApps - Combining all features

Support

For additional help:

  • Check the API Reference documentation
  • Visit DIYables tutorials: https://esp32io.com/tutorials/diyables-esp32-webapps
  • ESP32 community forums

※ OUR MESSAGES