使用UDP协议, 进行通信
●ESP32以AP模式运行
●ESP8266以STA模式运行
●ESP8266每五秒发送"hello"
●ESP32实时接受ESP8266发送的消息
ESP32
#include <WiFi.h>
#include <WiFiUDP.h>
const char AP_NameChar[] = "WIFI-SSID";
const char WiFiAPPSK[] = "WIFI-PSK";
IPAddress ESP8266ip1(192,168,4,2);
IPAddress ESP8266ip2(192,168,4,3);
IPAddress ESP8266ip(192,168,4,255);
unsigned int localPort =8080;
unsigned int remotePort=8080;
char incomingPacket[537];
char A;
WiFiUDP Udp;
void setup()
{
Serial.begin(9600);
WiFi.mode(WIFI_AP);
WiFi.softAP(AP_NameChar, WiFiAPPSK);
Udp.begin(localPort);
Serial.println();
Serial.println("Started ap. Local ip: " + WiFi.softAPIP().toString());
Serial.begin(9600);
}
void loop()
{
int packetSize = Udp.parsePacket();
if (packetSize)
{
Serial.printf("Received %d bytes from %s, port %d\n", packetSize, Udp.remoteIP().toString().c_str(), Udp.remotePort());
int len = Udp.read(incomingPacket, 536);
if (len > 0)
{
incomingPacket[len] = 0;
Serial.printf("UDP packet contents: %s\n", incomingPacket);
String COM=incomingPacket;
Serial.println(COM);
}
}
}