DIYables Web Apps Chat

WebChat Example - Setup Instructions

Overview

The WebChat example demonstrates how to create an interactive chat interface between a web browser and Arduino. Designed for Arduino Uno R4 WiFi and DIYables STEM V4 IoT educational platform with enhanced IoT capabilities and seamless integration with built-in sensors. The Arduino 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: Arduino provides contextual replies
  • LED Control: Control built-in LED via chat commands
  • User Recognition: Arduino remembers your name
  • Message History: View conversation history
  • Responsive Design: Works on desktop and mobile
  • Platform Extensible: Currently implemented for Arduino Uno R4 WiFi, but can be extended for other hardware platforms. See DIYables_WebApps_ESP32

Hardware Preparation

1×Arduino UNO R4 WiFi
1×Alternatively, DIYables STEM V4 IoT
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 Block Shield for Arduino UNO R4
1×Recommended: Breadboard Shield for Arduino UNO R4
1×Recommended: Enclosure for Arduino UNO R4
1×Recommended: Power Splitter for Arduino UNO R4
1×Recommended: Prototyping Base Plate & Breadboard Kit for Arduino UNO

Or you can buy the following kits:

1×DIYables STEM V4 IoT Starter Kit (Arduino included)
1×DIYables Sensor Kit (30 sensors/displays)
1×DIYables Sensor Kit (18 sensors/displays)
Disclosure: Some of the links provided in this section are Amazon affiliate links. We may receive a commission for any purchases made through these links at no additional cost to you.
Additionally, some of these links are for products from our own brand, DIYables .

Setup Instructions

Detailed Instructions

Follow these instructions step by step:

  • If this is your first time using the Arduino Uno R4 WiFi/DIYables STEM V4 IoT, refer to the tutorial on setting up the environment for Arduino Uno R4 WiFi/DIYables STEM V4 IoT in the Arduino IDE.
  • Connect the Arduino Uno R4/DIYables STEM V4 IoT board to your computer using a USB cable.
  • Launch the Arduino IDE on your computer.
  • Select the appropriate Arduino Uno R4 board (e.g., Arduino Uno R4 WiFi) and COM port.
  • Navigate to the Libraries icon on the left bar of the Arduino IDE.
  • Search "DIYables WebApps", then find the DIYables WebApps library by DIYables
  • Click Install button to install the library.
Arduino UNO R4 DIYables WebApps library
  • You will be asked for installing some other library dependencies
  • Click Install All button to install all library dependencies.
Arduino UNO R4 DIYables WebApps dependency
  • On Arduino IDE, Go to File Examples DIYables 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 Arduino responses * - Built-in LED control via chat commands * * Hardware: Arduino Uno R4 WiFi or DIYables STEM V4 IoT * * 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 <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 UnoR4ServerFactory 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 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 Arduino 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 Arduino Uno R4 WiFi! 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 Arduino UNO R4/DIYables STEM V4 IoT
  • 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: Arduino Uno R4 WiFi 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 Arduino 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:
Arduino UNO R4 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:
Arduino UNO R4 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 Arduino 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 Arduino uptime
  • "status" → Shows system status
Questions
  • "how are you?" → Arduino shares its status
  • "what can you do?" → Lists capabilities
  • "what is your name?" → Arduino introduces itself

Example Conversation

You: Hello Arduino: Hi there! I'm your Arduino assistant. What's your name? You: My name is John Arduino: Nice to meet you, John! I'm ready to help. You: led on Arduino: LED turned ON for you, John! 💡 You: what can you do? Arduino: I can control LEDs, respond to your messages, and remember your name. Try saying 'help' for commands! You: help Arduino: 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 Arduino 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 Arduino 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. Arduino 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 Arduino 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
  • Arduino 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://newbiely.com/tutorials/arduino-uno-r4/arduino-uno-r4-diyables-webapps
  • Arduino community forums

※ OUR MESSAGES

  • As freelancers, We are AVAILABLE for HIRE. See how to outsource your project to us
  • Please feel free to share the link of this tutorial. However, Please do not use our content on any other websites. We invested a lot of effort and time to create the content, please respect our work!