ESP32 TCP Client Example: Tutorial & Code
The ESP32, a low-cost microcontroller sporting Wi-Fi and dual-mode Bluetooth, is a versatile tool for IoT projects. A crucial aspect of Internet of Things (IoT) devices is client-server communication, often achieved using TCP (Transmission Control Protocol). This article explores a TCP client example for the ESP32, leveraging the popular Espressif's IDF (ESP-IDF) framework and its TCP stack.
Before diving in, ensure your ESP32 development environment is set up, including the appropriate components in your project, such as the `lwip Titus TCP/IP stack`, a C/C++ optimizer, and the necessary dependencies.
Setting Up the TCP Client
Begin by including the necessary headers:
Next, initialize constants for host, port, and buffer size:
```cpp #define HOST "example.com" #define PORT 80 #define BUFFER_SIZE 128 ```Creating a Socket
The `socket()` function creates a new socket, bound to a specific address family (usually PF_INET for IPv4) and communication protocol:
Verify steps to take when socket creation fails.
Connecting to the Server
The `connect()` function Initialize the server address structure (`server_addr`) and attempt to connect to the server:
```cpp struct sockaddr_in server_addr; memset(&server_addr, 0, sizeof(server_addr)); server_addr.sin_family = AF_INET; server_addr.sin_port = htons(PORT); server_addr.sin_addr.s_addr = inet_addr(HOST); if (connect(sock, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) { ESP_LOGE("TCP", "Error occurred during connect: errno %d", errno); return -1; } ```Be sure to add error handling code for a failed connection.
Sending and Receiving Data
Now that the connection is established, you can send and receive data.Sending Data