本帖最后由 roc2 于 2019-9-25 09:49 編輯
本帖主要講解ESP8266 WIFI功能關(guān)于UDP協(xié)議網(wǎng)絡(luò)傳輸?shù)膽?yīng)用,這里演示了ESP8266在AP模式下UDP通信的示例: 1、硬件 - 零知ESP8266開發(fā)板 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;
-
- // 復(fù)位或上電后運行一次:
- void setup() {
- //在這里加入初始化相關(guān)代碼,只運行一次:
- Serial.begin(115200);
-
- WiFi.softAP("Wi-Fi");
- Udp.begin(UDPPort);
- Serial.println();
- Serial.println("Started ap. Local ip: " + WiFi.localIP().toString());
- }
-
- //一直循環(huán)執(zhí)行:
- void loop() {
- // 在這里加入主要程序代碼,重復(fù)執(zhí)行:
- // 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();
- }
- }
復(fù)制代碼
(2)將上述代碼驗證后上傳到零知ESP8266,然后打開串口調(diào)試 窗口,可以看到如下信息:
1.jpg (59.47 KB, 下載次數(shù): 51)
下載附件
2019-9-24 13:48 上傳
(3)上面步驟完成后我們已經(jīng)把ESP8266作為一個熱點,SSID名字為"WI-FI”,可以在電腦上看到如下信息:
2.jpg (59.72 KB, 下載次數(shù): 46)
下載附件
2019-9-24 13:48 上傳
3.jpg (29.03 KB, 下載次數(shù): 41)
下載附件
2019-9-24 13:48 上傳
(4)我們打開零知工具箱,然后填寫好IP地址和端口號,點擊【連接】后就可以和ESP8266進行通信了。 3、測試驗證: 可以在串口調(diào)試窗口和零知工具箱發(fā)送接收區(qū)看到如下數(shù)據(jù)傳輸信息:
4.jpg (171.78 KB, 下載次數(shù): 46)
下載附件
2019-9-24 13:48 上傳
|