roc2two 发表于 2019-9-24 09:36

【零知ESP8266教程】AP模式下WIFI UDP协议通信示例

本帖最后由 roc2two 于 2019-9-25 09:53 编辑

本帖主要讲解ESP8266 WIFI功能关于UDP协议网络传输的应用,这里演示了ESP8266在AP模式下UDP通信的示例:
1、硬件:
零知ESP8266开发板2、软件(1)代码如下:/**********************************************************
      
*    文件: udp-server.ino      by 零知实验室(www.lingzhilab.com)
      
*    -^^- 零知开源,让电子制作变得更简单! -^^-
      
*    时间: 2019/06/17 11:42
      
*    说明:
      
************************************************************/
      
#include <ESP8266WiFi.h>
      
#include <WiFiUDP.h>
      

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

      
char packetBuffer; //buffer to hold incoming packet
      
charReplyBuffer[] = "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 = 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、测试验证:可以在串口调试窗口和零知工具箱发送接收区看到如下数据传输信息:
页: [1]
查看完整版本: 【零知ESP8266教程】AP模式下WIFI UDP协议通信示例