Practical guide to ESP8266 for TCP 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 TCP 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) $1.14 | |
1x ESP8266 Arduino adapter (recommended) $1.23 | |
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 TCP server
When the ESP8266 is set up as a TCP server, it listens for incoming connections from clients. This mode is useful for applications where the ESP8266 needs to serve data to multiple devices, such as a web server or a data logger. In the following snippet, the module is first set up as a soft access point and then configured as a TCP server. This allows you to access it without needing external networks. Just replace the defined constants with your desired network credentials.
#include "ESP8266WiFi.h"
#define NETWORK_NAME "ESP8266"
#define NETWORK_PASS "secure password"
#define TCP_SERVER_PORT 2000
#define TCP_CLIENT_TIMEOUT 30000 // 30 seconds inactivity timeout
WiFiServer server(TCP_SERVER_PORT);
unsigned long lastClientActivity = 0;
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();
server.setNoDelay(true); //Do not wait for big packet to send
Serial.println("Server started");
}
void loop()
{
WiFiClient client;
Serial.print("Waiting connections");
do {
client = server.available();
Serial.print(".");
delay(1000);
} while (!client);
Serial.println(" (done)");
while (client.connected()) {
if (client.available() > 0) {
lastClientActivity = millis();
String text = client.readString();
Serial.println("Received from the client: " + text);
client.flush();
// Send a message back to the client
Serial.print("Sending a message to the client... ");
client.println("Hello from ESP8266");
Serial.println("(done)");
}
// Check for client timeouts
if (lastClientActivity > 0 && lastClientActivity + TCP_CLIENT_TIMEOUT < millis()) {
break;
}
}
Serial.print("Client disconnecting... ");
client.stop();
Serial.println("(done)");
}
The loop code will wait for a client connection. Once established, it will read the incoming data and send a hello message back to the client. Additionally, any connection that remains inactive for more than the duration specified in the TCP_CLIENT_TIMEOUT constant (in milliseconds) will be automatically disconnected.
Flashing TCP 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 TCP 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 a client connection, we'll use the netcat tool. Any other tool capable of establishing a TCP connection can also be used for testing. The following command will establish a connection to the server.
netcat 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. The command will establish a connection with the server and enable message sending. The Serial Monitor will show the received text, and the client will automatically receive a hello message in response.
Configuring ESP8266 module as a TCP client
In TCP client mode, the ESP8266 initiates connections to a server. This mode is handy for applications where the ESP8266 needs to send data to a central server for processing. 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"
#define NETWORK_NAME "network-name"
#define NETWORK_PASS "network-pass"
#define TCP_SERVER_IP "192.168.1.46"
#define TCP_SERVER_PORT 2000
WiFiClient 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("Connecting to the host");
do {
Serial.print(".");
delay(1000);
} while (!client.connect(TCP_SERVER_IP, TCP_SERVER_PORT));
Serial.println(" (done)");
Serial.print("Sending a message to the host... ");
client.print("Hello from the client");
Serial.println("(done)");
while (client.connected()) {
if (client.available() > 0) {
String text = client.readString();
Serial.println("Received from the host: " + text);
}
}
Serial.print("Disconnecting... ");
client.stop();
Serial.println("(done)");
delay(5000);
}
The loop code will attempt to connect to the specified server. If the connection is successfully established, it will send a hello message and then wait for incoming data from the server.
Flashing TCP 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 TCP client on ESP8266
To simulate a TCP server, we'll use the netcat tool. Any other tool capable of creating a TCP server can also be used for testing. The following command will start listening for incoming connections on port 2000.
netcat -l -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. Once the connection is established, it will interact with the host and send a hello message. You should come across responses similar to those shown in the image below.
By verifying the server, we should see the hello message and be able to communicate with the client.
The Serial Monitor will display any message the client receives from the server.
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