Introduction
The ESP32 is a powerful microcontroller that offers Wi-Fi and Bluetooth connectivity, making it a popular choice for IoT applications. One of the most useful features of the ESP32 is its support for WebSocket, a protocol that enables real-time communication between a client and a server. In this article, we will explore the ESP32 WebSocket example and how it can be used to create powerful IoT applications.
What is WebSocket?
WebSocket is a protocol that enables real-time, bidirectional communication between a client and a server. Unlike HTTP, which is a request-response protocol, WebSocket allows for continuous communication between the client and server. This makes it ideal for applications that require real-time updates, such as chat applications, online games, and IoT applications.
ESP32 WebSocket Example
To demonstrate the ESP32 WebSocket example, we will create a simple IoT application that displays the temperature and humidity readings from a DHT11 sensor in real-time. The application will consist of an ESP32 microcontroller, a DHT11 sensor, and a WebSocket server.
Components Required
- ESP32 microcontroller
- DHT11 sensor
- Breadboard
- Jumper wires
- USB cable
Wiring
The DHT11 sensor has four pins: VCC, Data, NC, and GND. Connect the VCC pin to the 3.3V pin on the ESP32, the Data pin to GPIO 22, and the GND pin to the GND pin on the ESP32.
Note: Make sure to connect the DHT11 sensor to the ESP32 before powering it on.
Setting Up the WebSocket Server
To set up the WebSocket server, we will use Node.js and the ws module. Follow these steps to set up the WebSocket server:
- Install Node.js on your computer.
- Create a new folder for your project.
- Open a command prompt or terminal in the project folder.
- Install the ws module by running the following command:
npm install ws
This will install the ws module and its dependencies.
Next, create a new file called server.js in the project folder and add the following code:
Code:
“`const WebSocket = require(‘ws’);
const wss = new WebSocket.Server({ port: 8080 });
wss.on(‘connection’, function connection(ws) {console.log(‘Client connected’);
ws.on(‘message’, function incoming(message) {console.log(‘received: %s’, message);});
ws.send(‘Connected to server’);});“`
This code creates a new WebSocket server on port 8080 and listens for incoming connections. When a client connects to the server, it logs a message to the console and sends a message back to the client.
Setting Up the ESP32
To set up the ESP32, we will use the Arduino IDE and the ESPAsyncWebServer library. Follow these steps to set up the ESP32:
- Download and install the Arduino IDE from the official website.
- Open the Arduino IDE and go to File > Preferences.
- In the Additional Boards Manager URLs field, add the following URL:
https://dl.espressif.com/dl/package_esp32_index.json
This adds the ESP32 board package to the Arduino IDE.
- Go to Tools > Board > Boards Manager.
- Search for “esp32” and install the ESP32 board package.
- Go to Sketch > Include Library > Manage Libraries.
- Search for “ESPAsyncWebServer” and install the library.
This installs the necessary libraries for programming the ESP32.
Next, create a new sketch in the Arduino IDE and add the following code:
Code:
“`#include
const char* ssid = “your_SSID”;const char* password = “your_PASSWORD”;
const char* webSocketServerAddress = “ws://your_server_IP:8080”;
const int DHTPIN = 22;const int DHTTYPE = DHT11;DHT dht(DHTPIN, DHTTYPE);
AsyncWebServer server(80);WebSocketsServer webSocket(81);
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”);
server.on(“/”, HTTP_GET, [](AsyncWebServerRequest *request){request->send(200, “text/html”, “
“);});webSocket.begin();webSocket.onEvent(webSocketEvent);
dht.begin();}
void loop() {webSocket.loop();
float temperature = dht.readTemperature();float humidity = dht.readHumidity();
if (isnan(temperature) || isnan(humidity)) {Serial.println(“Failed to read from DHT sensor”);return;}
String message = “{ \”temperature\”: ” + String(temperature) + “, \”humidity\”: ” + String(humidity) + ” }”;webSocket.broadcastTXT(message);}
void webSocketEvent(uint8_t num, WStype_t type, uint8_t *payload, size_t length) {switch (type) {case WStype_CONNECTED:Serial.printf(“[%u] Connected\n”, num);break;case WStype_DISCONNECTED:Serial.printf(“[%u] Disconnected\n”, num);break;case WStype_TEXT:Serial.printf(“[%u] Received text: %s\n”, num, payload);break;}}“`
This code sets up the ESP32 to connect to the Wi-Fi network, start a web server on port 80, and a WebSocket server on port 81. It also initializes the DHT11 sensor and reads the temperature and humidity values in the loop function. When new values are read, it broadcasts them to all connected clients using the broadcastTXT function.
Conclusion
In this article, we have explored the ESP32 WebSocket example and how it can be used to create powerful IoT applications. We have also learned about the WebSocket protocol and its benefits for real-time communication. With the ESP32 and WebSocket, the possibilities for IoT applications are endless.
FAQ
What is the WebSocket protocol?
The WebSocket protocol is a protocol that enables real-time, bidirectional communication between a client and a server. Unlike HTTP, which is a request-response protocol, WebSocket allows for continuous communication between the client and server.
What is the ESP32?
The ESP32 is a powerful microcontroller that offers Wi-Fi and Bluetooth connectivity, making it a popular choice for IoT applications.
What is Node.js?
Node.js is an open-source, cross-platform JavaScript runtime environment that executes JavaScript code outside of a web browser. It is commonly used for building server-side applications and web applications.