标题: 零知ESP8266 AP模式下WIFI UDP协议通信示例 [打印本页]

作者: roc2    时间: 2019-9-24 13:49
标题: 零知ESP8266 AP模式下WIFI UDP协议通信示例
本帖最后由 roc2 于 2019-9-25 09:49 编辑

本帖主要讲解ESP8266 WIFI功能关于UDP协议网络传输的应用,这里演示了ESP8266在AP模式下UDP通信的示例:
1、硬件
- 零知ESP8266开发板  
2、软件
(1)代码如下:
  1. #include <WiFiUDP.h>

  2. unsigned int UDPPort = 8888;      // local port to listen on

  3. char packetBuffer[255]; //buffer to hold incoming packet
  4. char  ReplyBuffer[] = "acknowledged";       // a string to send back
  5. WiFiUDP Udp;

  6. // 复位或上电后运行一次:
  7. void setup() {
  8.         //在这里加入初始化相关代码,只运行一次:
  9.         Serial.begin(115200);
  10.          
  11.         WiFi.softAP("Wi-Fi");
  12.         Udp.begin(UDPPort);
  13.         Serial.println();
  14.         Serial.println("Started ap. Local ip: " + WiFi.localIP().toString());
  15. }

  16. //一直循环执行:
  17. void loop() {
  18.         // 在这里加入主要程序代码,重复执行:
  19.         // if there's data available, read a packet
  20.         int packetSize = Udp.parsePacket();
  21.         if (packetSize) {
  22.                 Serial.print("Received packet of size ");
  23.                 Serial.println(packetSize);
  24.                 Serial.print("From ");
  25.                 IPAddress remoteIp = Udp.remoteIP();
  26.                 Serial.print(remoteIp);
  27.                 Serial.print(", port ");
  28.                 Serial.println(Udp.remotePort());
  29.                  
  30.                 // read the packet into packetBufffer
  31.                 int len = Udp.read(packetBuffer, 255);
  32.                 if (len > 0) {
  33.                         packetBuffer[len] = 0;
  34.                 }
  35.                 Serial.println("Contents:");
  36.                 Serial.println(packetBuffer);
  37.                 // send a reply, to the IP address and port that sent us the packet we received
  38.                 Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
  39.                 Udp.write(ReplyBuffer);
  40.                 Udp.endPacket();
  41.         }
  42. }
复制代码

(2)将上述代码验证后上传到零知ESP8266,然后打开串口调试 窗口,可以看到如下信息:



(3)上面步骤完成后我们已经把ESP8266作为一个热点,SSID名字为"WI-FI”,可以在电脑上看到如下信息:



(4)我们打开零知工具箱,然后填写好IP地址和端口号,点击【连接】后就可以和ESP8266进行通信了。
3、测试验证:
可以在串口调试窗口和零知工具箱发送接收区看到如下数据传输信息:







欢迎光临 (http://www.51hei.com/bbs/) Powered by Discuz! X3.1