ESP32 Ap模式Udp通信
#include <WiFi.h>
#include <WiFiUdp.h>

const char* ssid = "ESP32-AP";      // AP 名称
const char* password = "12345678";  // 密码(至少8位)

WiFiUDP Udp;
const int localUdpPort = 4210;      // UDP监听端口
char incomingPacket[255];           // 存储接收到的数据
char replyPacket[] = "UDP Packet Received"; // 回复内容

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

  // 启动 Wi-Fi AP
  WiFi.mode(WIFI_AP);
  WiFi.softAP(ssid, password);
  Serial.println("WiFi AP started");
  Serial.println(WiFi.softAPIP()); // 打印AP的IP地址

  // 启动UDP监听
  Udp.begin(localUdpPort);
  Serial.printf("UDP server started at port %d\n", localUdpPort);
}

void loop() {
  int packetSize = Udp.parsePacket();
  if (packetSize) {
    // 接收到UDP数据包
    int len = Udp.read(incomingPacket, 255);
    if (len > 0) {
      incomingPacket[len] = 0;
    }
    Serial.printf("Received UDP packet: %s\n", incomingPacket);
    Serial.printf("From IP: %s, port: %d\n", Udp.remoteIP().toString().c_str(), Udp.remotePort());

    // 回复客户端
    Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
    Udp.write(replyPacket);
    Udp.endPacket();
  }

  delay(10);
}
上一篇