ESP32 IDF development application? Wifi UDP communication

ESP32 IDF development application? Wifi UDP communication

    • 1. The blogger’s purpose for writing this technical article:
    • 2. Overview
    • 3. Introduction to Socket API library
    • 4. Software design
    • 5. Examples


Don’t get lost-Navigation bar
Quickly navigate to find what you want (article directory)


If this article is useful to you, please like and save it. Your support is the motivation for the blogger to persist.

1. The blogger’s purpose of writing this technical article:

(1) Understand the communication characteristics of tcp udp;
(2), master udp programming;

2. Overview

In the previous chapter, we have introduced the basic applications of ESP32 WIFI STA and AP mode. This chapter is developed based on the wifi STA mode. I won’t introduce too much theoretical knowledge of Tcp here. You can explain it much better on Baidu than I can.
Advantages and disadvantages of TCP and UDP:
·TCP is connection-oriented, that is, a connection needs to be established before sending data; UDP is connection-oriented, that is, there is no need to establish a connection before sending data.
·TCP provides reliable services. In other words, the data transmitted through the TCP connection is error-free, not lost, not repeated, and arrives in order; UDP does its best to be reliable, that is, it does not guarantee absolute reliability.
·UDP has better real-time performance and higher working efficiency than TCP. It is suitable for communications or broadcast communications that require high-speed transmission and real-time performance.
·Each TCP connection can only be point-to-point; UDP supports one-to-one, one-to-many, many-to-one and many-to-many interactive communications.
·TCP requires more system resources, while UDP requires less system resources.

3. Introduction to Socket API library

1. The general steps for UDP programming client are:
(1) Create a UDP socket and use the socket() function;
(2) Use the sendto() function to send information to the specified IP address;
2. The general steps on the server side of UDP programming are:
(1) Create a UDP socket using socket();
(2) Set the attributes of the socket and use the setsockopt() function, (optional);
(3) Bind the (IPv4) structure containing IP information and address information. Use bind();
(4) To receive messages in a loop, use the recvfrom() function;
(5) Close the socket socket;
ESP32 uses LwIP, which is a small open source TCP/IP protocol stack especially suitable for embedded devices.
Storage resources are very small. ESP-IDF transplants the LwIP protocol stack.
We directly use the standard socket API interface here. The API functions are only briefly introduced. For detailed socket API, you can refer to Baidu
? Create connection socket ();
? Close socket function: close();
? Get socket error code: getsocketopt();
? Receive data function: recvfrom ();
?Send data function: sendto ();
For more APIs, please refer to esp-idf\components\lwip\lwip\src\include\lwip\sockets.h

4. Software design

(1), Client software design
①. Wait for wifi sta to connect to the router (the prerequisite is to set the ssid and password first)
②Create a socket to connect to the server

udp_connect_socket = socket(AF_INET, SOCK_DGRAM, 0);

③. Configure connection server information, port and IP
 udp_client_addr.sin_family = AF_INET;
    udp_client_addr.sin_port = htons(port);
    udp_client_addr.sin_addr.s_addr = inet_addr(ip);

④. Then send the data directly

sendto(udp_connect_socket, databuff, 30, 0, (struct sockaddr *)
& amp;udp_client_addr,sizeof(udp_client_addr));

5. Example

For new projects, please refer to the example section of [ESP32 IDF Development Application? Wifi TCP Client and Server Communication]
Part of the Wifi sta code is the same as the previous article and is not listed here.
Code: udp_bsp.c

#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>

#include "sdkconfig.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_system.h"
#include "esp_spi_flash.h"
#include "esp_wifi.h"

#include <sys/socket.h>
#include "freertos/event_groups.h"
#include "esp_event.h"
#include "esp_err.h"
#include "nvs_flash.h"
#include "esp_smartconfig.h"
#include "esp_netif.h"
#include "esp_wpa2.h"

#include "esp_log.h"
#include "esp_ota_ops.h"
#include "nvs.h"
#include "udp_bsp.h"

//task handle
static TaskHandle_t xHandleTaskUdp = NULL;

//Task stack size, mainly the memory of function nested parameters and local variables
#define Udp_TASK_STACK_SIZE 8192

//Task priority, the bigger it is, the higher it is, opposite to ucos
#define Udp_TASK_PRIO 2

static int udp_connect_socket = 0; //Client connects to socket
static struct sockaddr_in udp_client_addr; //client address

//Function declaration
static void vTaskUdp(void *pvParameters);
static esp_err_t CreateUdpClient(const char *ip,uint16_t port);

/****************************************************** **********************
* Function:
* Description: Create tcp receiving and sending tasks for external use
* Parameters:
* Return: None
* Remark:
*************************************************** **********************/
void AppTaskCreate(void)
{<!-- -->
    xTaskCreate(vTaskUdp, //Task function
            "vTaskUdp", // task name
            Udp_TASK_STACK_SIZE, // Task stack size, unit word, which is 4 bytes
            NULL, //Task parameters
            Udp_TASK_PRIO, //Task priority
             & amp;xHandleTaskUdp); //Task handle
}
/****************************************************** **********************
* Function:
* Description: Create UDP client connection
* Parameters: ip: IP address, port: port number
* Return: None
* Remark:
*************************************************** **********************/
static esp_err_t CreateUdpClient(const char *ip,uint16_t port)
{<!-- -->
    //Waiting for a successful connection, or if the connection is already disconnected, this function will always block until there is a connection.
   EventBits_t bits = xEventGroupWaitBits(xCreatedEventGroup_WifiConnect,//Event flag group handle
                        WIFI_CONNECTED_BIT, // Wait for bit0 and bit1 to be set
                        pdFALSE, //bit0 and bit1 are cleared when TRUE exits, bit0 and bit1 are not cleared when pdFALSE exits
                        pdFALSE, //Set to pdTRUE to wait for both bit1 and bit0 to be set, pdFALSE to wait for either bit1 or bit0 to be set
                        portMAX_DELAY); //Wait for the delay time and keep waiting
    if (bits & WIFI_CONNECTED_BIT)
    {<!-- -->
        //Create new socket
        udp_connect_socket = socket(AF_INET, SOCK_DGRAM, 0); /*Parameters are different from TCP*/
        if (udp_connect_socket < 0)
        {<!-- -->
            //After the new creation fails, close the newly created socket and wait for the next creation.
            close(udp_connect_socket);
            return ESP_FAIL;
        }
        //Configure connection server information
        udp_client_addr.sin_family = AF_INET;
        udp_client_addr.sin_port = htons(port);
        udp_client_addr.sin_addr.s_addr = inet_addr(ip);
        int len = 0; //Length
        char databuff[30] = "Hello Server, Please ack!!"; // Regardless of whether there is a connection or not, send a wave of data first.
        //Test udp server and return the length of successful transmission
        len = sendto(udp_connect_socket, databuff, 30, 0, (struct sockaddr *) & amp;udp_client_addr,sizeof(udp_client_addr));
        if (len > 0)
        {<!-- -->
        }
        else
        {<!-- -->
            close(udp_connect_socket);
            return ESP_FAIL;
        }
        return ESP_OK;
    }
    else
    {<!-- -->
        return ESP_FAIL;
    }
}
/****************************************************** **********************
* Function:
* Description: Client tasks
* Parameters:
* Return: None
* Remark:
*************************************************** **********************/
static void vTaskUdp(void *pvParameters)
{<!-- -->
    int len = 0; //Length
    uint8_t databuff[512]; //caching
    //Create udp client
    CreateUdpClient(UDP_CLIENT_ADDRESS,UDP_CLIENT_PORT);
    unsigned int udpsocklen = sizeof(udp_client_addr); //Address length
    for (;;)
    {<!-- -->
        //Read the received data
        memset(databuff,0,sizeof(databuff));
        len = recvfrom(udp_connect_socket, databuff, sizeof(databuff), 0,(struct sockaddr *) & amp;udp_client_addr, & amp;udpsocklen);
        if (len > 0)//Receive data
        {<!-- -->
            printf("UDP REV: %s\
",(char *)databuff);
            sendto(udp_connect_socket, databuff, len , 0,(struct sockaddr *) & amp;udp_client_addr, sizeof(udp_client_addr));
        }
        else
        {<!-- -->
            //Disconnect
            CreateUdpClient(UDP_CLIENT_ADDRESS,UDP_CLIENT_PORT);
            vTaskDelay(500/portTICK_PERIOD_MS);
        }
        vTaskDelay(50/portTICK_PERIOD_MS);
    }
}

Code: udp_bsp.h

#ifndef __UDP_BSP_H__
#define __UDP_BSP_H__
#ifdef __cplusplus
extern "C" {<!-- -->
#endif
 //As UDP CLIENT, 255.255.255.255, indicating closing data
 //If you need to send to the specified IP, enter the other party's IP directly here.
#define UDP_CLIENT_ADRESS "255.255.255.255"
#define UDP_CLIENT_PORT 4000 //UDP client port

#define WIFI_CONNECTED_BIT BIT0
#define WIFI_FAIL_BIT BIT1
extern EventGroupHandle_t xCreatedEventGroup_WifiConnect;

void AppTaskCreate(void);


#ifdef __cplusplus
}
#endif
#endif /*#ifndef __UDP_BSP_H__*/

During testing, if the connection cannot be made, press the rst button first.

All article source codes: https://download.csdn.net/download/lu330274924/88518092