Introduction
WebSocket is a protocol that provides a bi-directional, full-duplex communication channel over a single TCP connection. It is a powerful tool for real-time web applications and Internet of Things (IoT) projects. The Arduino and ESP8266 are popular platforms for building IoT projects due to their low-cost and ease of use. In this article, we will explore how to use WebSocket with Arduino and ESP8266.
What is WebSocket?
WebSocket is a protocol that provides a full-duplex communication channel over a single TCP connection. Unlike HTTP, which is a request-response protocol, WebSocket allows for bi-directional communication between the client and the server. This means that the server can send data to the client without the client having to first request it. WebSocket is ideal for real-time web applications such as chat rooms, online games, and stock tickers.
What is Arduino?
Arduino is an open-source electronics platform based on easy-to-use hardware and software. It is designed to be used by artists, designers, and hobbyists who want to create interactive objects or environments. Arduino boards are programmed using a simplified version of C++ and can be connected to a wide range of sensors, motors, and other devices.
What is ESP8266?
ESP8266 is a low-cost Wi-Fi microchip with full TCP/IP stack and microcontroller capability. It is commonly used in IoT projects due to its low cost, ease of use, and built-in Wi-Fi connectivity. ESP8266 can be programmed using the Arduino IDE and can be integrated with a wide range of sensors, devices, and cloud platforms.
WebSocket with Arduino
WebSocket can be used with Arduino to build real-time web applications and IoT projects. The following steps outline how to use WebSocket with Arduino:
- Install the Ethernet library in the Arduino IDE
- Connect the Ethernet shield to the Arduino board
- Create a WebSocket server on the Arduino board
- Handle incoming WebSocket messages
- Send WebSocket messages to the client
1. Install the Ethernet library in the Arduino IDE
The Ethernet library is required to connect the Arduino board to the internet. To install the Ethernet library, follow these steps:
- Open the Arduino IDE
- Click on Sketch > Include Library > Manage Libraries…
- Type “Ethernet” in the search bar
- Select the Ethernet library from the list and click on “Install”
2. Connect the Ethernet shield to the Arduino board
The Ethernet shield is used to connect the Arduino board to the internet. To connect the Ethernet shield to the Arduino board, follow these steps:
- Insert the Ethernet shield onto the Arduino board
- Connect an Ethernet cable to the Ethernet shield
- Connect the other end of the Ethernet cable to a router or modem
3. Create a WebSocket server on the Arduino board
To create a WebSocket server on the Arduino board, follow these steps:
- Include the Ethernet library at the beginning of your sketch with the following code:
- Create an Ethernet server object with the following code:
- Start the Ethernet server with the following code:
- Create a WebSocket server object with the following code:
- Handle incoming WebSocket messages with the following code:
- Run the Ethernet and WebSocket servers with the following code:
#include <Ethernet.h>
EthernetServer server(80);
The “80” in the code above specifies the port number. You can use any available port number.
server.begin();
WebSocketsServer webSocket = WebSocketsServer(81);
The “81” in the code above specifies the WebSocket port number. You can use any available port number.
void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t length) {
switch(type) {
case WStype_DISCONNECTED:
Serial.printf("[%u] Disconnected!\n", num);
break;
case WStype_CONNECTED:
{
IPAddress ip = webSocket.remoteIP(num);
Serial.printf("[%u] Connected from %d.%d.%d.%d url: %s\n", num, ip[0], ip[1], ip[2], ip[3], payload);
}
break;
case WStype_TEXT:
Serial.printf("[%u] Received text: %s\n", num, payload);
webSocket.sendTXT(num, "Got your text");
break;
}
}
The code above handles incoming WebSocket messages and sends a response back to the client.
void loop() {
EthernetClient client = server.available();
if (client) {
while (client.connected()) {
webSocket.loop();
}
}
}
The code above runs the Ethernet and WebSocket servers and handles incoming client connections.
4. Handle incoming WebSocket messages
To handle incoming WebSocket messages, use the webSocketEvent() function that we created in step 3. The webSocketEvent() function is called whenever a new WebSocket message is received from the client. The function takes four parameters:
- num: The client number
- type: The WebSocket message type (e.g. text, binary, ping, pong)
- payload: The WebSocket message payload
- length: The length of the WebSocket message payload
You can use the switch statement in the webSocketEvent() function to handle different types of WebSocket messages. For example, you can use the following code to handle text messages:
case WStype_TEXT:
Serial.printf("[%u] Received text: %s\n", num, payload);
webSocket.sendTXT(num, "Got your text");
break;
The code above sends a response back to the client with the message "Got your text".
5. Send WebSocket messages to the client
To send WebSocket messages to the client, use the webSocket.send() function. The function takes two parameters:
- num: The client number
- payload: The WebSocket message payload
For example, you can use the following code to send a text message to the client:
webSocket.sendTXT(num, "Hello World!");
The code above sends the message "Hello World!" to the client with the specified client number.
WebSocket with ESP8266
WebSocket can also be used with ESP8266 to build real-time web applications and IoT projects. The following steps outline how to use WebSocket with ESP8266:
- Install the ESP8266 board in the Arduino IDE
- Connect ESP8266 to Wi-Fi
- Create a WebSocket server on ESP8266
- Handle incoming WebSocket messages
- Send WebSocket messages to the client
1. Install the ESP8266 board in the Arduino IDE
To use ESP8266 with the Arduino IDE, you need to install the ESP8266 board in the Arduino IDE. To install the ESP8266 board, follow these steps:
- Open the Arduino IDE
- Click on File > Preferences
- Enter the following URL in the "Additional Boards Manager URLs" field:
- Click "OK"
- Click on Tools > Board > Boards Manager...
- Type "esp8266" in the search bar
- Select the "esp8266" board from the list and click on "Install"
http://arduino.esp8266.com/stable/package_esp8266com_index.json
2. Connect ESP8266 to Wi-Fi
To connect ESP8266 to Wi-Fi, use the following code:
#include <ESP8266WiFi.h>
const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
}
The code above connects ESP8266 to the Wi-Fi network with the specified SSID and password.
3. Create a WebSocket server on ESP8266
To create a WebSocket server on ESP8266, use the following code:
#include <WebSocketsServer.h>
WebSocketsServer webSocket = WebSocketsServer(81);
void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t length) {
switch(type) {
case WStype_DISCONNECTED:
Serial.printf("[%u] Disconnected!\n", num);
break;
case WStype_CONNECTED:
{
IPAddress ip = webSocket.remoteIP(num);
Serial.printf("[%u] Connected from %d.%d.%d.%d url: %s\n", num, ip[0], ip[1], ip[2], ip[3], payload);
}
break;
case WStype_TEXT:
Serial.printf("[%u] Received text: %s\n", num, payload);
webSocket.sendTXT(num, "Got your text");
break;
}
}
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
webSocket.begin();
webSocket.onEvent(webSocketEvent);
}
void loop() {
webSocket.loop();
}
The code above creates a WebSocket server on ESP8266 and handles incoming WebSocket messages.
4. Handle incoming WebSocket messages
To handle incoming WebSocket messages, use the webSocketEvent() function