基于arduino的esp32 udp组播接收程序
时间: 2023-08-14 15:05:43 浏览: 85
以下是基于Arduino的ESP32 UDP组播接收程序示例:
```c
#include <WiFi.h>
#include <WiFiUdp.h>
const char* ssid = "YOUR_WIFI_SSID";
const char* password = "YOUR_WIFI_PASSWORD";
const uint16_t multicastPort = 1900;
const IPAddress multicastIP(239, 255, 255, 250);
WiFiUDP udp;
void setup() {
Serial.begin(115200);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
if (!udp.beginMulticast(WiFi.localIP(), multicastIP, multicastPort)) {
Serial.println("Failed to begin multicast");
while (1) {
delay(1000);
}
}
Serial.println("Multicast receiver started");
}
void loop() {
static char rx_buffer[128];
int packetSize = udp.parsePacket();
if (packetSize) {
IPAddress remoteIP = udp.remoteIP();
uint16_t remotePort = udp.remotePort();
int len = udp.read(rx_buffer, sizeof(rx_buffer) - 1);
if (len > 0) {
rx_buffer[len] = 0;
Serial.printf("Received %d bytes from %s:%d\n", len, remoteIP.toString().c_str(), remotePort);
Serial.println(rx_buffer);
} else {
Serial.println("Failed to receive data");
}
}
}
```
在这个示例中,我们首先连接WiFi。然后,我们创建一个UDP套接字并将其绑定到本地IP地址和端口。接下来,我们加入多播组并等待接收数据。当数据到达时,我们打印接收到的数据和来源地址和端口。
阅读全文