【得捷Follow me第4期】W5500-EVB-Pico PIO UDP收发测试
[复制链接]
本帖最后由 wo4fisher 于 2024-3-2 17:58 编辑
1. 新建基础工程并添加Ethernet3库文件到工程目录
2. UDP协议收发代码编辑
Internet 协议集支持一个无连接的传输协议,该协议称为用户数据报协议(UDP,User Datagram Protocol)。UDP 为应用程序提供了一种无需建立连接就可以发送封装的 IP 数据包的方法。
即UDP基于无连接,通过IP地址和端口即可以收发数据。
上代码:
- #include <Arduino.h>
- #include <SPI.h>
- #include <Ethernet3.h>
- #include <EthernetUdp3.h>
-
-
-
-
- byte mac[] = {
- 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
- };
- IPAddress ip(192, 168, 2, 177);
-
- unsigned int localPort = 8888;
-
-
- char packetBuffer[UDP_TX_PACKET_MAX_SIZE];
- char ReplyBuffer[] = "acknowledged";
-
-
- EthernetUDP Udp;
-
- void setup() {
-
- Ethernet.setCsPin(17);
- Ethernet.setRstPin(20);
-
-
- Ethernet.begin(mac, ip);
- Udp.begin(localPort);
-
- Serial.begin(115200);
- }
-
- void loop() {
-
- int packetSize = Udp.parsePacket();
- if (packetSize)
- {
- Serial.print("Received packet of size ");
- Serial.println(packetSize);
- Serial.print("From ");
- IPAddress remote = Udp.remoteIP();
- for (int i = 0; i < 4; i++)
- {
- Serial.print(remote[i], DEC);
- if (i < 3)
- {
- Serial.print(".");
- }
- }
- Serial.print(", port ");
- Serial.println(Udp.remotePort());
-
-
- Udp.read(packetBuffer, UDP_TX_PACKET_MAX_SIZE);
- Serial.println("Contents:");
- Serial.println(packetBuffer);
-
-
- Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
- Udp.write(ReplyBuffer);
- Udp.endPacket();
- }
- delay(10);
- }
-
-
-
主要步骤:
第一步:定义mac地址、本机ip地址、端口号和EthernetUDP 实例。
第二步:在setup中
初始化/定义cs引脚和rst引脚,
Ethernet.begin(mac, ip);初始化网络参数
Udp.begin(localPort);启动UDP服务器
第三步:在loop中
监听Udp.parsePacket(),如果有数据,进行解析
Udp.read()读取数据并通过串口输出后,再通过Udp.write()函数进行应答。
other:
UDP客户端实例就会以上例子反过来,因为UDP为无连接协议。因此
大概思路就是:
实例化UDP
封装发送数据
通过
Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
Udp.write(ReplyBuffer);
Udp.endPacket();
进行发送
然后解析、读取应答数据
Udp.parsePacket();
Udp.read(packetBuffer, UDP_TX_PACKET_MAX_SIZE);
需要的话增加超时判断(可能没有应答)即可。
|