本帖最后由 roc2 于 2019-9-25 09:49 编辑
本帖主要讲解ESP8266 WIFI功能关于UDP协议网络传输的应用,这里演示了ESP8266在AP模式下UDP通信的示例: 1、硬件 - 零知ESP8266开发板 2、软件 (1)代码如下: - #include <WiFiUDP.h>
-
- unsigned int UDPPort = 8888; // local port to listen on
-
- char packetBuffer[255]; //buffer to hold incoming packet
- char ReplyBuffer[] = "acknowledged"; // a string to send back
- WiFiUDP Udp;
-
- // 复位或上电后运行一次:
- void setup() {
- //在这里加入初始化相关代码,只运行一次:
- Serial.begin(115200);
-
- WiFi.softAP("Wi-Fi");
- Udp.begin(UDPPort);
- Serial.println();
- Serial.println("Started ap. Local ip: " + WiFi.localIP().toString());
- }
-
- //一直循环执行:
- void loop() {
- // 在这里加入主要程序代码,重复执行:
- // if there's data available, read a packet
- int packetSize = Udp.parsePacket();
- if (packetSize) {
- Serial.print("Received packet of size ");
- Serial.println(packetSize);
- Serial.print("From ");
- IPAddress remoteIp = Udp.remoteIP();
- Serial.print(remoteIp);
- Serial.print(", port ");
- Serial.println(Udp.remotePort());
-
- // read the packet into packetBufffer
- int len = Udp.read(packetBuffer, 255);
- if (len > 0) {
- packetBuffer[len] = 0;
- }
- Serial.println("Contents:");
- Serial.println(packetBuffer);
- // send a reply, to the IP address and port that sent us the packet we received
- Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
- Udp.write(ReplyBuffer);
- Udp.endPacket();
- }
- }
复制代码
(2)将上述代码验证后上传到零知ESP8266,然后打开串口调试 窗口,可以看到如下信息:
(3)上面步骤完成后我们已经把ESP8266作为一个热点,SSID名字为"WI-FI”,可以在电脑上看到如下信息:
(4)我们打开零知工具箱,然后填写好IP地址和端口号,点击【连接】后就可以和ESP8266进行通信了。 3、测试验证: 可以在串口调试窗口和零知工具箱发送接收区看到如下数据传输信息:
|