ESP32 UDP communication

1. Introduction to UDP communication

UDP: Data can be sent without establishing a connection.

HTTP: Both parties need to establish a connection to send data.

Detailed introduction link:

https://blog.csdn.net/qq_39300332/article/details/79139229

2. Test UDP communication

For example, what is UDP communication?

We are accustomed to using the "ping" command to test whether the TCP/IP communication between two hosts is normal. If the incoming news is fed back in time, then the network is connected.

We are using esp32 development board to test UDP communication.

1. Download the network debugging assistant NetAssist. The icon looks like this (hahaha, it looks so strange):

 First of all, let's click on it to have a look, remember the IP address and port number, we will use it later. Note: Afterwards, the network connected to ESP32 and the network used by the computer are under the same WiFi.

 2. Go directly to the code test.

#include <WiFi.h>
#include <WiFiUdp.h> //引用以使用UDP

const char *ssid = "***";
const char *password = "***";

WiFiUDP Udp;                      //创建UDP对象
unsigned int localUdpPort = 8080; //本地端口号

void setup()
{
  Serial.begin(115200);
  Serial.println();

  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  while (!WiFi.isConnected())
  {
    delay(500);
    Serial.print(".");
  }
  Serial.println("Connected");
  Serial.print("IP Address:");
  Serial.println(WiFi.localIP());

  Udp.begin(localUdpPort); //启用UDP监听以接收数据
}

void loop()
{
  int packetSize = Udp.parsePacket(); //获取当前队首数据包长度
  if (packetSize)                     //如果有数据可用
  {
    char buf[packetSize];
    Udp.read(buf, packetSize); //读取当前包数据
    Serial.print("message: ");
    Serial.println(buf);
    Serial.print("From IP: ");
    Serial.println(Udp.remoteIP());
    Serial.print("From Port: ");
    Serial.println(Udp.remotePort());

  }
}

The above code example is esp32 receiving data as UDP.

We open the network debugging assistant and the serial port assistant.

First look at the IP address of esp32 on the serial port assistant.

Then open the network debugging assistant, as follows, the boxed area is the target host, which is the IP and port of esp32:

 The port number we set in the program is 8080.

 Then send data casually and test it. Look at the serial port reception on the esp side.

 Above, the esp32 can receive the data, but there are more garbled characters in the back, and the communication is unreliable.

Guess you like

Origin blog.csdn.net/weixin_58125062/article/details/129844656