ESP8266 Arduino UDP: 发送位置数据并接收经纬度
以下是一个使用ESP8266和Arduino发送UDP请求数据,并接收经纬度数据的示例代码:
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
const char* ssid = 'your_SSID';
const char* password = 'your_PASSWORD';
WiFiUDP udp;
char packetBuffer[255];
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println('Connecting to WiFi...');
}
Serial.println('Connected to WiFi');
}
void loop() {
if (WiFi.status() == WL_CONNECTED) {
// 发送UDP请求
udp.beginPacket('192.168.101.14', 6677);
udp.print('position');
udp.endPacket();
// 等待接收UDP响应
int packetSize = udp.parsePacket();
if (packetSize) {
int len = udp.read(packetBuffer, 255);
if (len > 0) {
packetBuffer[len] = 0;
}
Serial.print('Received packet: ');
Serial.println(packetBuffer);
}
delay(5000); // 每隔5秒发送一次请求
}
}
请确保将your_SSID和your_PASSWORD替换为您的WiFi网络的SSID和密码。在setup()函数中,代码会等待ESP8266连接到WiFi网络。一旦连接成功,loop()函数将每隔5秒发送一次UDP请求,并等待接收UDP响应。接收到的响应数据将通过串口打印出来。
在udp.beginPacket('192.168.101.14', 6677);中,将192.168.101.14替换为您要发送UDP请求的目标IP地址。
原文地址: https://www.cveoy.top/t/topic/qklx 著作权归作者所有。请勿转载和采集!