下面是使用Arduino接收UDP传来的数据
//下面是一个使用ESP8266模块通过Arduino IDE读取UDP数据的示例代码。这段代码将ESP8266配置为一个UDP客户端,它会连接到指定的服务器IP地址和端口,并监听发送到该服务器的数据。
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
// 网络配置
const char* ssid = "ChinaNet-ggzf";
const char* password = "jelkjxlawav";
// UDP配置
IPAddress udpServerIP(192, 168, 1, 4); // 服务器IP地址
const int udpPort = 1010; // 服务器端口号
WiFiUDP udp;
unsigned int localUdpPort = 1200; // 本地UDP端口号,可以任选
void setup() {
Serial.begin(115200);
// 连接到Wi-Fi网络
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
// 开启UDP
udp.begin(localUdpPort);
}
void sendUdpMessage() {
//Serial.println("Sending UDP message to server...");
udp.beginPacket(IPAddress, udpPort);
udp.write("lianjie-ok");
udp.endPacket();
// Serial.println("Message sent.");
}
void loop() {
//
// 等待UDP数据包
int packetSize = udp.parsePacket();
if (packetSize) {
// 如果收到数据包,读取它
//Serial.print("Received packet of size ");
// Serial.println(packetSize);
int len = udp.available();
if (len > 0) {
// 读取数据
char packetBuffer[50];
int len = udp.read(packetBuffer, 50);
if (len > 0) {
packetBuffer[len] = 0;
Serial.println("Contents: ");
Serial.println(packetBuffer);
if(packetBuffer=="判断条件"){}
}
}
}
}