Arduino UNO R4 - WebSocket

This guide explains what WebSocket is, why it is helpful for using Arduino UNO R4, and how to use WebSocket with Arduino UNO R4. We will show you how to create a chat application that lets a web browser communicate with Arduino UNO R4, allowing you to:

Arduino UNO R4 websocket

Hardware Preparation

1×Arduino UNO R4 WiFi
1×USB Cable Type-C
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

Or you can buy the following sensor kits:

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.

What is Arduino UNO R4 Websocket?

You may ask, "What is WebSocket?" It's simple: WebSocket is a technology that allows a web browser to talk directly with a web server instantly.

  • Without WebSocket, you must reload the webpage to view new updates. This is not very convenient.
  • With WebSocket, the webpage stays constantly connected to the server. This means they can share information immediately without reloading the page.

You often use WebSocket technology in daily web applications like online games, instant messaging, and stock market updates.

Why we need WebSocket to smoothly control Arduino UNO R4?

Suppose you want to control a remote-controlled car using your smart phone or computer's web browser. If you don't use WebSocket, you would have to refresh the web page every time you wish to change the car's direction or speed. It is similar to pressing a "reload" button every time you give a command to the car.

WebSocket allows a constant and direct connection between your web browser and the car. You can control the car's direction and speed without needing to refresh the page. It's like the car instantly responds to your commands in real-time, with no delays from reloading the page.

WebSocket makes it easier to:

  • Sending data from the web browser to Arduino UNO R4 without having to reload the webpage.
  • Sending data back to the web browser from Arduino UNO R4 without needing to refresh the page.

This allows for easy back-and-forth conversation in real time.

Benefits of WebSocket with Arduino UNO R4:

  • Real-Time Control: WebSocket allows immediate interaction with the Arduino UNO R4, enabling fast responses to your commands for a smooth experience.
  • Persistent Connection: Keep a constant connection without needing to refresh the control page, ensuring a communication line that's always ready for direct instructions.
  • Efficiency: Enjoy quick replies and a better experience without having to reload the page repeatedly, making it more efficient and enjoyable.

Web Chat with Arduino UNO R4 via WebSocket

The webpage's materials like HTML, CSS, and JavaScript are kept in a separate file named index.h. So in the Arduino IDE, we will use two code files.

  • A .ino file is Arduino UNO R4 code. It sets up a web server and a WebSocket server.
  • A .h file contains the content for the webpage.

Detailed Instructions

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 “mWebSockets” and locate the mWebSockets by Dawid Kurek.
  • Click on the Install button to add the mWebSockets library.
Arduino UNO R4 mWebSockets library
  • In the Arduino IDE, create a new sketch and name it, for example, newbiely.com.ino
  • Copy the following code and open it in Arduino IDE
/* * This Arduino UNO R4 code was developed by newbiely.com * * This Arduino UNO R4 code is made available for public use without any restriction * * For comprehensive instructions and wiring diagrams, please visit: * https://newbiely.com/tutorials/arduino-uno-r4/arduino-uno-r4-websocket */ #include <WiFiS3.h> #include <WebSocketServer.h> #include "index.h" using namespace net; WebSocketServer wss(81); WiFiServer server(80); const char ssid[] = "YOUR_WIFI_SSID"; // change your network SSID const char pass[] = "YOUR_WIFI_PASSWORD"; // change your network password int status = WL_IDLE_STATUS; void setup() { //Initialize serial and wait for port to open: Serial.begin(9600); String fv = WiFi.firmwareVersion(); if (fv < WIFI_FIRMWARE_LATEST_VERSION) Serial.println("Please upgrade the firmware"); // attempt to connect to WiFi network: while (status != WL_CONNECTED) { Serial.print("Attempting to connect to SSID: "); Serial.println(ssid); // Connect to WPA/WPA2 network. Change this line if using open or WEP network: status = WiFi.begin(ssid, pass); // wait 4 seconds for connection: delay(4000); } // print your board's IP address: Serial.print("IP Address: "); Serial.println(WiFi.localIP()); server.begin(); wss.onConnection([](WebSocket &ws) { const auto protocol = ws.getProtocol(); if (protocol) { Serial.print(F("Client protocol: ")); Serial.println(protocol); } ws.onMessage([](WebSocket &ws, const WebSocket::DataType dataType, const char *message, uint16_t length) { switch (dataType) { case WebSocket::DataType::TEXT: Serial.print(F("Received: ")); Serial.println(message); break; case WebSocket::DataType::BINARY: Serial.println(F("Received binary data")); break; } String reply = "Received: " + String((char *)message); ws.send(dataType, reply.c_str(), reply.length()); }); ws.onClose([](WebSocket &, const WebSocket::CloseCode, const char *, uint16_t) { Serial.println(F("Disconnected")); }); Serial.print(F("New WebSocket Connnection from client: ")); Serial.println(ws.getRemoteIP()); const char message[]{ "Hello from Arduino server!" }; ws.send(WebSocket::DataType::TEXT, message, strlen(message)); }); wss.begin(); } void loop() { wss.listen(); // listen for incoming clients WiFiClient client = server.available(); if (client) { // read the HTTP request header line by line while (client.connected()) { if (client.available()) { String HTTP_header = client.readStringUntil('\n'); // read the header line of HTTP request if (HTTP_header.equals("\r")) // the end of HTTP request break; Serial.print("<< "); Serial.println(HTTP_header); // print HTTP request to Serial Monitor } } // send the HTTP response header client.println("HTTP/1.1 200 OK"); client.println("Content-Type: text/html"); client.println("Connection: close"); // the connection will be closed after completion of the response client.println(); // the separator between HTTP header and body String html = String(HTML_CONTENT); client.println(html); client.flush(); // give the web browser time to receive the data delay(50); // close the connection: client.stop(); } }
  • Change the WiFi details (SSID and password) in the code to yours.
  • To make the index.h file in Arduino IDE:
    • Click the button below the serial monitor icon and select New Tab, or press Ctrl+Shift+N keys.
    Arduino IDE 2 adds file
    • Name the file as index.h and press the OK button.
    Arduino IDE 2 adds file index.h
    • Copy the following code and paste it into the index.h file.
    /* * This Arduino UNO R4 code was developed by newbiely.com * * This Arduino UNO R4 code is made available for public use without any restriction * * For comprehensive instructions and wiring diagrams, please visit: * https://newbiely.com/tutorials/arduino-uno-r4/arduino-uno-r4-websocket */ const char *HTML_CONTENT = R"=====( <!DOCTYPE html> <html> <head> <title>Arduino Uno R4 WebSocket</title> <meta name="viewport" content="width=device-width, initial-scale=0.7, maximum-scale=0.7"> <link rel="icon" href="https://diyables.io/images/page/diyables.svg"> <style> /* Add some basic styling for the chat window */ body { background-color: #E1EFEF; font-size: 20px; line-height: 1.3; } button, input { font-size: 20px; line-height: 1.3; } .chat-container { margin: 0 auto; padding: 10px; } .chat-messages { height: 250px; overflow-y: auto; padding: 5px; margin-bottom: 5px; } .user-input { display: flex; margin-bottom: 20px; } .user-input input { flex: 1; border: 1px solid #444; padding: 5px; } .user-input button { margin-left: 5px; background-color: #007bff; color: #fff; border: none; padding: 5px 10px; cursor: pointer; } .websocket { display: flex; align-items: center; margin-bottom: 5px; } .websocket button { background-color: #007bff; color: #fff; border: none; padding: 5px 10px; cursor: pointer; } .websocket .label { margin-left: auto; } .message-sent { border-radius: 25px; background-color: #d35400; float: right; width: fit-content; padding: 10px 20px; margin: 0; } .message-received { border-radius: 25px; background-color: white; float: left; width: fit-content; padding: 10px 20px; margin: 0; } </style> <script> var ws; var wsm_max_len = 4096; /* bigger length causes uart0 buffer overflow with low speed smart device */ function update_text(text) { var chat_messages = document.getElementById("chat-messages"); chat_messages.innerHTML += '<div style="width:100%;overflow: auto;">' + text + '</div>'; chat_messages.scrollTop = chat_messages.scrollHeight; } function send_onclick() { if(ws != null) { var message = document.getElementById("message").value; if (message) { document.getElementById("message").value = ""; ws.send(message + "\n"); update_text('<p class="message-sent">' + message + '</p>'); // You can send the message to the server or process it as needed } } } function connect_onclick() { if(ws == null) { ws = new WebSocket("ws://" + window.location.host + ":81"); document.getElementById("ws_state").innerHTML = "CONNECTING"; ws.onopen = ws_onopen; ws.onclose = ws_onclose; ws.onmessage = ws_onmessage; } else ws.close(); } function ws_onopen() { document.getElementById("ws_state").innerHTML = "<span style='color:blue'>CONNECTED</span>"; document.getElementById("bt_connect").innerHTML = "Disconnect"; document.getElementById("chat-messages").innerHTML = ""; } function ws_onclose() { document.getElementById("ws_state").innerHTML = "<span style='color:gray'>CLOSED</span>"; document.getElementById("bt_connect").innerHTML = "Connect"; ws.onopen = null; ws.onclose = null; ws.onmessage = null; ws = null; } function ws_onmessage(e_msg) { e_msg = e_msg || window.event; // MessageEvent console.log(e_msg.data); update_text('<p class="message-received">' + e_msg.data + '</p>'); } </script> </head> <body> <div class="chat-container"> <h2>Arduino Uno R4 WebSocket</h2> <div class="websocket"> <button class="connect-button" id="bt_connect" onclick="connect_onclick()">Connect</button> <span class="label">WebSocket: <span id="ws_state"><span style="color:blue">CLOSED</span></span></span> </div> <div class="chat-messages" id="chat-messages"></div> <div class="user-input"> <input type="text" id="message" placeholder="Type your message..."> <button onclick="send_onclick()">Send</button> </div> <div class="sponsor">Sponsored by <a href="https://amazon.com/diyables">DIYables</a></div> </div> </body></html> )=====";
    • You now have the code in two files: newbiely.com.ino and index.h.
    • Click the Upload button in Arduino IDE to upload code to your Arduino UNO R4.

    You will see an error message like this:

    In file included from c:\Users\YOU_ACCOUNT\Documents\Arduino\libraries\mWebSockets\src/utility.h:3:0, from c:\Users\YOU_ACCOUNT\Documents\Arduino\libraries\mWebSockets\src/WebSocket.h:5, from c:\Users\YOU_ACCOUNT\Documents\Arduino\libraries\mWebSockets\src/WebSocketServer.h:5, from C:\Users\YOU_ACCOUNT\Documents\Arduino\newbiely.com\newbiely.com.ino:2: C:\Users\YOU_ACCOUNT\Documents\Arduino\libraries\mWebSockets\src/platform.h:54:12: fatal error: Ethernet.h: No such file or directory # include <Ethernet.h> ^~~~~~~~~~~~ compilation terminated. exit status 1

    To solve this problem:

    • Navigate to the directory at C:\Users\YOUR_ACCOUNT\Documents\Arduino\libraries\mWebSockets\src/.
    • Locate the file named config.h and open it using a text editor.
    • Go to line 26 and you will see the following content:
    #define NETWORK_CONTROLLER ETHERNET_CONTROLLER_W5X00
    • Change the line as shown below and then save it:
    #define NETWORK_CONTROLLER NETWORK_CONTROLLER_WIFI
    • Click the Upload button in Arduino IDE to upload the code to Arduino UNO R4.
    • Open the Serial Monitor.
    • View the results on the Serial Monitor.
    COM6
    Send
    Connecting to WiFi... Connected to WiFi Arduino UNO R4 Web Server's IP address IP address: 192.168.0.2
    Autoscroll Show timestamp
    Clear output
    9600 baud  
    Newline  
    • Write down the IP address shown and type it into the web browser's address bar on your smartphone or computer.
    • The webpage will appear as described below:
    Arduino UNO R4 websocket web browser
    • Press the CONNECT button to link the webpage with Arduino UNO R4 using WebSocket.
    • Enter some text and send it to Arduino UNO R4.
    • Observe the reply from Arduino UNO R4.
    Arduino UNO R4 websocket chat server

    ※ NOTE THAT:

    • If you only change the HTML in the file named index.h and do not modify the file named newbiely.com.ino, the Arduino IDE will not update the HTML when you compile and upload the code to the Arduino UNO R4.
    • To update the HTML content through the Arduino IDE, make a small change in the newbiely.com.ino file, like adding an empty line or a comment.

    Line-by-line Code Explanation

    Please read the comments in the code for a line-by-line explanation of the above Arduino UNo R4 code.

How the System Works

The Arduino UNO R4 code sets up a web server and a WebSocket server. Here is how it functions:

  • Type the IP address of the Arduino UNO R4 into a web browser.
  • The Arduino UNO R4's web server sends the webpage (made of HTML, CSS, JavaScript) to your browser.
  • Your browser shows the webpage.
  • Click the CONNECT button on the webpage. This action starts a WebSocket connection with the server on the Arduino UNO R4.
  • If you type text and click the SEND button, the JavaScript sends your text to the Arduino UNO R4 through the WebSocket.
  • The WebSocket server on the Arduino UNO R4 receives your text and sends back a response to your webpage.

Here are other examples of Arduino UNO R4 WebSocket that you can learn:

Troubleshooting For Arduino Uno R4

If the above code does work, please update the latest version for the WiFi module of Arduino UNO R4

  • Connect your Arduino Uno R4 WiFi to your PC
  • Open Arduino IDE 2
  • Go to Tools Firmware Updater
Arduino Uno R4 WiFi Update Firmware
  • Select the Arduino Uno R4 WiFi board and port
  • Click CHECK UPDATES button
  • A list of available firmware versions will appear
  • Select the latest version of firmware
  • Click INSTALL button
  • Wait until it done
  • Reboot your Arduino Uno R4 WiFi
  • Re-compile and upload your code to Arduino Uno R4 WiFi
  • Check the result

※ 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!