Arduino Uno R4 WiFi Web Server Library Reference
Overview
The UnoR4WiFi_WebServer library provides a comprehensive solution for creating multi-page web servers with WebSocket support on Arduino Uno R4 WiFi and DIYables STEM V4 IoT boards.
Hardware Required
1 | × | Arduino UNO R4 WiFi | |
1 | × | Alternatively, DIYables STEM V4 IoT | |
1 | × | USB Cable Type-C |
Additionally, some links direct to products from our own brand, DIYables .
Examples
Installation
Quick Steps
Follow these instructions step by step:
- If this is your first time using the Arduino Uno R4 WiFi/Minima, refer to the tutorial on setting up the environment for Arduino Uno R4 WiFi/Minima in the Arduino IDE.
- Connect the Arduino Uno R4 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.
- Open the Library Manager by clicking on the Library Manager icon on the left side of the Arduino IDE.
- Search for Web Server for Arduino Uno R4 WiFi and locate the mWebSockets by DIYables.
- Click on the Install button to add the mWebSockets library.

WebSocket Support (Built-in)
WebSocket functionality is now integrated directly into this library!
The WebSocket implementation is based on the excellent mWebSockets library by skaarj1989, which has been integrated and optimized specifically for Arduino Uno R4 WiFi to make it easy to use:
- No additional library installation required - WebSocket support is built-in
- Optimized for Arduino Uno R4 WiFi - Simplified platform-specific implementation
- WiFiS3 compatibility - Uses Arduino Uno R4's native WiFi stack
- RFC 6455 compliant - Full WebSocket protocol support
- Real-time communication - Bidirectional data exchange
Usage:
- For everything (Web Server + WebSocket): Use #include <UnoR4WiFi_WebServer.h>
- That's it! - WebSocket functionality is automatically available when needed
- Memory efficient - Unused WebSocket code is automatically optimized out by the compiler
Credits: WebSocket implementation adapted from mWebSockets library (LGPL-2.1 License) by skaarj1989, modified and integrated for seamless Arduino Uno R4 WiFi compatibility.
Library Classes
UnoR4WiFi_WebServer Class
The main class for creating and managing web servers.
Constructor
Creates a web server instance on the specified port (default: 80).
Methods
begin()
Starts the web server and begins listening for incoming connections.
Overloaded versions:
- begin(): Start server only (WiFi must be connected separately by your application)
- begin(ssid, password): Connect to WiFi and start server in one call (legacy approach)
setNotFoundHandler()
Sets a custom handler for 404 Not Found responses.
printWifiStatus()
Prints WiFi connection status and IP address to Serial Monitor.
handleClient()
Processes incoming client requests. This should be called repeatedly in the main loop.
on()
Registers a handler function for a specific URI and HTTP method.
Parameters:
- uri: The URI path (e.g., "/", "/led", "/api/data")
- method: HTTP method (GET, POST, PUT, DELETE, etc.)
- fn: Handler function to execute when the route is accessed
Note: This library uses addRoute() method instead of on(). See below for correct usage.
addRoute()
Registers a handler function for a specific URI. This is the actual method used in the library.
RouteHandler Function Format:
Route handlers must follow this exact signature:
Parameters:
- client: WiFiClient reference for sending responses
- method: HTTP method as string ("GET", "POST", etc.)
- request: Full request URI
- params: Query parameters (QueryParams object)
- jsonData: JSON payload for POST requests (empty for GET)
Handler Implementation Examples:
- Basic GET Handler:
- JSON API Handler (GET and POST):
- Query Parameters Handler:
sendResponse()
Sends an HTTP response to the client.
Parameters:
- client: WiFiClient reference (provided in handler function)
- content: Response body content
- contentType: MIME type of the response (default: "text/html")
Usage Examples:
Authentication Methods
enableAuthentication()
Enables HTTP Basic Authentication for all routes. Once enabled, all routes require authentication.
Parameters:
- username: Username for authentication (max 31 characters)
- password: Password for authentication (max 31 characters)
- realm: Authentication realm displayed in browser (max 63 characters, optional)
Usage Example:
disableAuthentication()
Disables authentication, making all routes publicly accessible again.
Usage Example:
isAuthenticationEnabled()
Returns true if authentication is currently enabled, false otherwise.
Usage Example:
send401()
Sends a 401 Unauthorized response with proper WWW-Authenticate header. This is automatically called when authentication fails, but can be used manually in custom handlers.
Usage Example:
Manual Response Sending
For more control over HTTP headers and status codes:
Query Parameters Access
QueryParams Structure
The QueryParams object contains parsed query parameters from the URL:
Accessing Query Parameters
Parameter Helper Functions
Create helper functions for easier parameter access:
WebSocket Classes (Built-in)
WebSocketServer
Alias for net::WebSocketServer - simplified for beginner use.
WebSocket
Alias for net::WebSocket - represents a WebSocket connection.
WebSocket Methods
begin()
Starts the WebSocket server.
loop()
Processes WebSocket events. Call this in your main loop.
onConnection()
Sets callback for new WebSocket connections.
onMessage()
Sets callback for incoming WebSocket messages.
onClose()
Sets callback for WebSocket connection closures.
send()
Sends a message through the WebSocket.
close()
Closes the WebSocket connection.
Additional WebSocket Methods
broadcastTXT()
Broadcasts text message to all connected WebSocket clients.
broadcastBIN()
Broadcasts binary data to all connected WebSocket clients.
connectedClients()
Returns the number of currently connected WebSocket clients.
isListening()
Returns true if the WebSocket server is actively listening for connections.
WebSocket Event Types
DataType Enum
- WebSocket::DataType::TEXT - Text message type
- WebSocket::DataType::BINARY - Binary data type
CloseCode Enum
Standard WebSocket close codes for connection termination reasons.
Advanced WebSocket Usage
Event Handler Setup
Message Processing
Broadcasting Sensor Data
HTTP Methods
The library supports standard HTTP methods:
- HTTP_GET
- HTTP_POST
- HTTP_PUT
- HTTP_DELETE
- HTTP_PATCH
- HTTP_HEAD
- HTTP_OPTIONS
Client-Side JavaScript Integration
Basic WebSocket Connection
Sending Commands
Message Handling
WebSocket Examples
Simple Echo Server
JSON Command Processing
Heartbeat Implementation
WebSocket Troubleshooting
Common Issues
WebSocket Connection Failed
- Verify WebSocket server port (default: 81) is accessible
- Check firewall settings on both client and Arduino network
- Ensure Arduino IP address is correct and reachable
- Use browser developer tools to check WebSocket connection errors
Messages Not Being Received
- Check Serial Monitor for WebSocket event logs
- Verify JSON message format is correct
- Test with simple text messages before using JSON
- Ensure message length doesn't exceed buffer limits
Connection Drops Frequently
- Implement heartbeat/ping mechanism
- Check WiFi signal strength and stability
- Add connection retry logic in client code
- Monitor memory usage on Arduino
High Memory Usage
- Limit number of concurrent WebSocket connections
- Clear message buffers regularly
- Use efficient String handling (avoid frequent concatenation)
- Monitor free heap memory
Debug Helpers
Performance Monitoring
The library supports HTML templates with placeholder replacement:
Common placeholders:
- %TEMPERATURE% - Temperature value
- %LED_STATUS% - LED status
- %QUERY_PARAM% - Query parameter values
Advanced Web Server Features
CORS Support
Enable cross-origin requests for web applications:
JSON Response Helpers
Simplify JSON API development:
Request Validation
Implement robust input validation:
Enhanced JSON Processing
For complex JSON handling with ArduinoJson library:
Error Handling
Default 404 Handler
The library provides a default 404 error page. You can override it:
Best Practices
- Memory Management: Use F() macro for string literals stored in flash memory
- Non-blocking Code: Keep handler functions lightweight to avoid blocking the server
- Security: Validate input parameters and sanitize output
- Performance: Use appropriate HTTP status codes and content types
- WebSocket: Handle connection states properly and implement reconnection logic
Debugging
Enable serial debugging to monitor server activity:
Compatibility
- Arduino Uno R4 WiFi: Fully supported
- DIYables STEM V4 IoT: Fully supported
- WiFiS3 Library: Required (included with Arduino IDE)
- Memory Requirements: Minimum 32KB flash, 2KB RAM
Limitations
Web Server Limitations
- Maximum simultaneous HTTP connections: 4 (hardware limitation)
- Maximum URL length: 256 characters
- Template placeholders: No nested replacements
WebSocket Limitations
- Maximum WebSocket message size: 1KB per message
- Maximum concurrent WebSocket connections: 4-6 (depending on available memory)
- Fragment messages: Automatically handled but may impact performance
- Binary message size: Limited by available RAM
- Connection timeout: 60 seconds default (configurable)
Memory Constraints
- Minimum flash memory required: 32KB
- Minimum RAM required: 2KB for basic functionality
- WebSocket overhead: ~200-500 bytes per connection
- Message buffering: ~1KB per active connection
※ ARDUINO BUY RECOMMENDATION
Arduino UNO R3 | |
Arduino Starter Kit |