打印

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

[复制链接]
498|0
手机看帖
扫描二维码
随时随地手机跟帖
跳转到指定楼层
楼主
roc2two|  楼主 | 2019-9-20 11:36 | 只看该作者 |只看大图 回帖奖励 |倒序浏览 |阅读模式
本帖最后由 roc2two 于 2019-9-25 09:55 编辑

本帖主要讲解ESP8266 WIFI功能关于UDP协议网络传输的应用,这里演示了ESP8266在STATION模式下UDP通信的示例:
1、硬件
零知ESP8266

2、软件
(1)代码如下:
/**********************************************************
*    文件: esp8266-udp-clinet.ino      by 零知实验室(www.lingzhilab.com)
*    -^^- 零知开源,让电子制作变得更简单! -^^-
*    时间: 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");
}

//一直循环执行:
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开发板中,然后打开串口调试窗口,可以看到如下信息:

上面显示了ESP8266的IP地址和端口号信息。


(3)现在打开零知工具箱(可以在“软件下载”页面下载),然后打开“网络调试”界面,选择UDP模式并选择UDP的IP和端口号,如下:

TIP:零知工具箱请在零知实验室官网下载哦



3、测试验证
在零知工具箱中,点击【连接】,然后就可以和零知ESP8266开始通信了,我们在发送窗口填写发送的信息,点击【发送】,可以看到如下信息,表明通信双方成功:


使用特权

评论回复

相关帖子

发新帖 我要提问
您需要登录后才可以回帖 登录 | 注册

本版积分规则

75

主题

85

帖子

1

粉丝