Practical guide to ESP8266 for UDP servers and clients
The ESP8266 module has become a favorite among electronics enthusiasts for its low cost and powerful capabilities. This Wi-Fi module can be used in various ways, making it a versatile tool for many IoT applications. In this guide, we will explore how the ESP8266 can function as both a server and a client using UDP protocol.
Prerequisites
For a deeper understanding of the ESP8266WiFi library, we recommend reading the article Wi-Fi Integration made easy with ESP8266WiFi library, which provides a detailed guide on library setup and module wiring.
Components
1x ESP8266 module
| |
1x USB Serial adapter
| |
1x Mini-breadboard (recommended) $1.17 | |
1x ESP8266 breadboard adapter (recommended)
| |
1x ESP8266 Arduino adapter (recommended)
| |
Resistors kit $4.35 | |
Dupont wires
|
Wiring schema
Given that many commercially available devices operate on 5V logic, there is a risk of damage when directly connecting them with the ESP8266 module. It is important to note that each input signal to the ESP8266 should not exceed 3.3V, necessitating the use of a voltage divider for each signal departing to the module.
Before you can perform any updates, you need to properly connect your ESP8266 to your computer. Here's a step-by-step guide to the wiring schema:
Connect the 5V output of the CP2102 adapter to the VCC pin of the ESP8266 module to power it. Since the ESP8266 operates on 3.3V, do not connect it directly to 5V. Use a voltage regulator or a resistor divider to reduce the voltage to 3.3V. Additionally, enable the module by connecting the CH_PD pin to the 3.3V pin.
Connect the GND pin of the CP2102 adapter to the GND pin of the ESP8266 to complete the circuit.
Connect the RX pin of the CP2102 adapter to the TX pin of the ESP8266 module.
This connection does not require a voltage divider. This is because the ESP8266's TX pin outputs signals at 3.3V logic levels, which are compatible with the CP2102 module's TX pin operating at 5V logic levels.Connect the TX pin of the CP2102 adapter to the RX pin of the ESP8266 module via a voltage divider.
Use a voltage divider circuit with a 10Kohm resistor connected between the TX pin of the CP2102 adapter and the RX pin of the ESP8266 module. Additionally, connect a 20Kohm resistor between the RX pin of the ESP8266 module and ground (GND). The junction between the two resistors will provide the appropriate voltage level for the RX pin of the ESP8266 module.To enter the flashing mode, connect GPIO0 to the ground (GND) before powering on or resetting the ESP8266. This is necessary for uploading new code to the ESP8266 module and can be easily accomplished by turning the switch button ON. When the code has been uploaded and you only want to use the module, the switch must be turned OFF.
The voltage divider setup ensures that the 5V output from the Arduino's TX pin is reduced to approximately 3.3V, which is safe for the ESP8266 module. Make sure to double-check your connections and use appropriate resistor values to achieve the desired voltage reduction.
Alternatively, you can use existing adapters for the ESP8266 module, which simplify the wiring depending on your needs. For more information on detailed wiring and adapters, refer to the article Wi-Fi Integration made easy with ESP8266WiFi library.
Install ESP8266WiFi library
The ESP8266WiFi library abstracts the complexities of Wi-Fi communication, providing a simple and straightforward way to connect your projects to the internet. This library includes a variety of features, such as network scanning, connecting to a network, and managing multiple connections. By using the ESP8266WiFi library, developers can focus more on their application's core functionality rather than getting bogged down with networking details.
The Wi-Fi library for ESP8266 has been developed based on ESP8266 SDK, using the naming conventions and overall functionality philosophy of the Arduino WiFi library. Before using the library, there's a configuring step for ESP8266 board.
ESP8266 board configuration
Navigate to the File menu and select Preferences. In the Preferences window, you will find a field labeled Additional Board Manager URLs. Here, you need to enter the following URL:
http://arduino.esp8266.com/stable/package_esp8266com_index.json
After pasting the URL, save your changes and close the Preferences window.
Next, you need to install the ESP8266 board package. To do this, go to the Tools menu, hover over Board, and then click on Boards Manager. A new window will open, allowing you to manage different board packages. In the search bar at the top of this window, type ESP8266. Look for the esp8266 by ESP8266 Community package and click on the install button next to it. This process may take a while, so be patient while the package is being downloaded and installed.
After the installation is complete, you need to select the appropriate ESP8266 board from the list. Go back to the Tools menu, hover over Board, and scroll through the list of available boards until you find the one that matches your hardware, such as ESP8266 Generic Module. Click on it to select it as your active board.
From this point forward, you can simply use the include statement:
#include "ESP8266WiFi.h"
It will include the library with predefined functions to interact with the module.
Configuring ESP8266 module as a UDP server
As a UDP server, the ESP8266 listens for UDP packets from clients. This mode is useful for applications that require low-latency communication, such as sensor networks. In the following snippet, the module is first set up as a soft access point and then configured as an UDP server. This allows you to access it without needing external networks. Just replace the defined constants with your desired network credentials
#include "ESP8266WiFi.h"
#include "WiFiUdp.h"
#define NETWORK_NAME "ESP8266"
#define NETWORK_PASS "secure password"
#define UDP_SERVER_PORT 2000
WiFiUDP server;
void setup()
{
// Begin serial communication with the host computer
Serial.begin(115200);
Serial.println();
// Wait
delay(1000);
// Setup soft-AP for communication
const bool softAp = WiFi.softAP(NETWORK_NAME, NETWORK_PASS);
Serial.print("Setting soft-AP... ");
Serial.println(softAp ? "(done)" : "(failed)");
Serial.println("IP address: " + WiFi.softAPIP().toString());
// Configuring server
server.begin(UDP_SERVER_PORT);
Serial.println("Server started");
}
void loop()
{
if (server.parsePacket() > 0) {
String text = server.readString();
Serial.println("Received from the client: " + text);
// Send a message back to the client
Serial.print("Sending a message to the client... ");
server.beginPacket(server.remoteIP(), server.remotePort());
server.println("Hello from ESP8266");
server.endPacket();
Serial.println("(done)");
}
}
The loop code will wait for incoming data, read it, and print it to the Serial Monitor.
Flashing UDP server code to ESP8266
To upload new code to the ESP8266 module, it must be set to flashing mode as specified in the wiring schema. The upload process may take some time and will produce output similar to the image shown below.
Once the upload is complete, disconnect the module, turn off flashing mode, and reconnect it to begin using it.
Testing UDP server on ESP8266
After connecting the ESP8266 module, it will establish a soft access point, configure the server, and display the results on the serial monitor. You should come across responses similar to those shown in the image below.
The module is now configured as an access point, so a connection to this access point is required to establish communication with the module.
To simulate UDP communication, we'll use the netcat tool. Alternatively, any tool that can send UDP messages can be used for testing. The following command will enable interaction with the UDP server by allowing messages to be sent to it.
netcat -u ESP8266_IP 2000
Replace ESP8266_IP with the IP address displayed on the Serial Monitor (in the current example 192.168.4.1). The default port for the connection is set to 2000. When the client sends a message, a hello response will be automatically sent back.
The Serial Monitor will display any message the server receives from the client.
Configuring ESP8266 module as a UDP client
When operating as a UDP client, the ESP8266 sends packets to a UDP server. This setup is suitable for applications that need to broadcast data or send periodic updates. In the following snippet, the module needs to connect to an available WiFi network. Simply replace the defined constants with your network credentials. Additionally, make sure to assign the correct server IP address.
#include "ESP8266WiFi.h"
#include <WiFiUdp.h>
#define NETWORK_NAME "network-name"
#define NETWORK_PASS "network-pass"
#define UDP_SERVER_IP "192.168.1.46"
#define UDP_SERVER_PORT 2000
WiFiUDP client;
void setup()
{
// Begin serial communication with the host computer
Serial.begin(115200);
Serial.println();
// Wait
delay(1000);
// Begin wireless communication with the network
WiFi.begin(NETWORK_NAME, NETWORK_PASS);
Serial.print("Connecting");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println(" (done)");
// Successfully connected
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
}
void loop()
{
Serial.print("Sending a message to the host... ");
client.beginPacket(UDP_SERVER_IP, UDP_SERVER_PORT);
client.println("Hello from the client");
client.endPacket();
Serial.println("(done)");
delay(5000);
}
The loop code will send a hello message to the server every 5 seconds.
Flashing UDP client code to ESP8266
To upload new code to the ESP8266 module, it must be set to flashing mode as specified in the wiring schema. The upload process may take some time and will produce output similar to the image shown below.
Once the upload is complete, disconnect the module, turn off flashing mode, and reconnect it to begin using it.
Testing UDP client on ESP8266
To simulate an UDP server, we'll use the netcat tool. Any other tool capable of creating a UDP server can also be used for testing. The following command will start listening for incoming messages on port 2000.
netcat -l -u -p 2000
After connecting the ESP8266 module, it will establish a connection with the specified WiFi access point displaying the results on the serial monitor. Then, a hello message will be sent to the server every 5 seconds. You should come across responses similar to those shown in the image below.
By verifying the server, we should see the hello messages received every 5 seconds.
Conclusion
The ESP8266 module offers diverse functionalities, making it a go-to option for various IoT projects. Its capability to act as both a server and a client, using either TCP or UDP protocols, provides flexibility for developers. Whether you're creating a web server, sending sensor data, or setting up a communication network, the ESP8266 can handle the task efficiently. With simple code examples and tools like netcat, you can quickly test and deploy your applications, bringing your IoT ideas to life.
Credits
Official GitHub: https://github.com/hibit-dev/ESP8266
Official ESP8266WiFi: https://arduino-esp8266.readthedocs.io
This article is available to HiBit members only.
If you're new to HiBit, create a free account to read this article.
0 Comments