本帖主要講解ESP8266 WIFI功能關于UDP協(xié)議網(wǎng)絡傳輸?shù)膽,這里演示了ESP8266在STATION模式下UDP通信的示例:
1、硬件
零知ESP8266
1.png (183.59 KB, 下載次數(shù): 31)
下載附件
2019-9-25 10:18 上傳
2、軟件
(1)代碼如下:
- /**********************************************************
- * 文件: esp8266-udp-clinet.ino by 零知實驗室
- * -^^- 零知開源,讓電子制作變得更簡單! -^^-
- * 時間: 2019/06/17 11:01
- * 說明:
- ************************************************************/
- #include <ESP8266WiFi.h>
- #include <WiFiUDP.h>
- #define SSID "xx"
- #define PSSWD "xx"
- unsigned int UDPPort = 8888; // local port to listen on
- char packetBuffer[255]; //buffer to hold incoming packet
- char replyBuffer[] = "send-back-ack"; // a string to send back
- WiFiUDP Udp;
- // 復位或上電后運行一次:
- void setup() {
- //在這里加入初始化相關代碼,只運行一次:
- Serial.begin(115200);
- WiFi.mode(WIFI_STA);
- WiFi.begin(SSID, PSSWD);
- while (WiFi.status() != WL_CONNECTED) {
- Serial.print('.');
- delay(500);
- }
- Serial.print("Connected! IP address: ");
- Serial.println(WiFi.localIP());
- Serial.printf("UDP server on port %d\n", UDPPort);
- Udp.begin(UDPPort);
-
- // Udp.beginPacket("192.168.4.1", UDPPort);//send ip to server
- // char ipBuffer[255];
- // WiFi.localIP().toString().toCharArray(ipBuffer, 255);
- // Udp.write(ipBuffer);
- // Udp.endPacket();
- // Serial.println("Sent ip adress to server");
- }
- //一直循環(huán)執(zhí)行:
- void loop() {
- // 在這里加入主要程序代碼,重復執(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();
- }
- }
復制代碼 (2)將上面代碼驗證后并上傳到零知ESP8266開發(fā)板中,然后打開串口調(diào)試窗口,可以看到如下信息:
2.jpg (116.88 KB, 下載次數(shù): 20)
下載附件
2019-9-25 10:18 上傳
上面顯示了ESP8266的IP地址和端口號信息。
(3)現(xiàn)在打開零知工具箱(可以在“軟件下載”頁面下載),然后打開“網(wǎng)絡調(diào)試”界面,選擇UDP模式并選擇UDP的IP和端口號,如下:
TIP:零知工具箱請在零知實驗室官網(wǎng)下載哦
3.jpg (279.38 KB, 下載次數(shù): 26)
下載附件
2019-9-25 10:18 上傳
3、測試驗證 在零知工具箱中,點擊【連接】,然后就可以和零知ESP8266開始通信了,我們在發(fā)送窗口填寫發(fā)送的信息,點擊【發(fā)送】,可以看到如下信息,表明通信雙方成功:
4.jpg (311.12 KB, 下載次數(shù): 25)
下載附件
2019-9-25 10:18 上傳
更多精彩請訪問零知官網(wǎng) |