了解使用 W5100S-EVB-Pico 板和 Arduino IDE 构建快速高效的 UDP 发送器。 非常适合实时网络通信!
转发: Mastering Packet Transmission with the W5100S-EVB-Pico UDP Sender
项目介绍
欢迎来到用户数据报协议 (UDP) 的世界,这是一种以速度和效率而自豪的网络通信方法。 UDP 能够通过网络发送数据包,而无需在发送方和接收方之间建立直接连接,从而简化了网络通信,同时节省了宝贵的资源。 现在,我们向您介绍一款可以无缝融入该生态系统的设备 - W5100S-EVB-Pico 板。
让我们深入研究使用 W5100S-EVB-Pico 板与 Arduino IDE 的强大功能来创建 UDP 发送器的细节。 然而,请记住,虽然 UDP 在速度和资源消耗方面超过了 TCP,但它缺乏对数据包或其顺序的保证传送。 但不用担心,因为在许多用例中,特别是在实时交互至关重要的情况下,这种权衡绝对是值得的。
要点
要开始这个激动人心的旅程,您需要准备一些物品:
- W5100S-EVB-Pico 板,
- Arduino 集成开发环境,
- 适用于 W5100S-EVB-Pico 的 WIZnet 以太网库,以及
- 充当 UDP 接收器的设备或应用程序,侦听指定的远程 IP 地址和端口。
搭建舞台
一旦掌握了要点,设置过程就很简单:
- 在 Arduino IDE 中安装 W5100S-EVB-Pico 的 WIZnet 以太网库。
- 将 W5100S-EVB-Pico 板连接到计算机。
- 在 Arduino IDE 中打开提供的示例。
- 配置remoteIP 变量以匹配您想要的UDP 接收器的IP 地址。
- 将remotePort 变量设置为UDP 接收器的端口号。
- 将草图上传到您的 W5100S-EVB-Pico 板。 瞧,设置完成了!
代码
#include <SPI.h>
#include <Ethernet.h>
#include <EthernetUdp.h>
// Enter a MAC address for your controller below.
byte mac[] = {
0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
};
const int csPin = 17; // Chip Select (CS) pin for W5100S on W5100S-EVB-Pico
const int localPort = 8888; // Local port to listen on
const int remotePort = 9999; // Remote port to send to
char packetBuffer[UDP_TX_PACKET_MAX_SIZE]; // Buffer to hold incoming packets
IPAddress remoteIP(192, 168, 0, 2); // Remote IP address to send UDP packets to
EthernetUDP Udp;
void setup() {
// Open the serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
// Initialize Ethernet with the CS pin:
Ethernet.init(csPin);
// Start the Ethernet connection using DHCP:
Serial.println("Attempting to obtain IP address using DHCP...");
if (Ethernet.begin(mac) == 0) {
Serial.println("Failed to obtain IP address using DHCP");
} else {
// Print the obtained IP address:
Serial.print("Successfully obtained IP address: ");
Serial.println(Ethernet.localIP());
}
// Initialize the UDP instance and start listening on the local port
Udp.begin(localPort);
}
void loop() {
// Send a UDP packet to the remote IP and port
Udp.beginPacket(remoteIP, remotePort);
Udp.write("Hello, UDP Receiver!");
Udp.endPacket();
// Wait for a while before sending the next packet
delay(2000);
}
实现UDP传输
设置后,您可以按如下方式监控该过程:
- 在 Arduino IDE 中打开串行监视器。
- 该草图将首先尝试使用 DHCP 获取 IP 地址。 成功后,该 IP 地址将显示在串行监视器中。
- 每两秒,草图就会发送一个“Hello, UDP Receiver!” 消息发送到指定的远程 IP 地址和端口。
串行监视器不会显示发送的消息,但会显示通过 DHCP 获取的 IP 地址。
行动中
Attempting to obtain IP address using DHCP...
Successfully obtained IP address: 192.168.1.100
串行监视器中的输出将显示获得的 IP 地址。 “你好,UDP 接收器!” 消息将每 2 秒发送到指定的远程 IP 和端口,但这不会显示在串行监视器中。
友情提醒
确保您的远程设备或应用程序(充当 UDP 接收器)已正确配置为侦听指定 IP 地址和端口上的传入数据包。 虽然此示例重点关注发送 UDP 数据包,但请记住,要接收和处理传入数据包,您将需要实现 UDP 接收器。
从本质上讲,掌握使用 W5100S-EVB-Pico 板进行 UDP 数据包传输的技术为高效、实时的网络通信开辟了无数的可能性。 是时候跳入快节奏的 UDP 领域了!
文件