【发布时间】:2017-06-26 04:34:00
【问题描述】:
我正在编写与两个 arduino 通信的代码,一个带有以太网屏蔽,另一个带有 ENC28J60 以太网模块。我不是 arduino 的新手,也不是明智/专家。但在 UDP 通信方面,我是一个完整的新手。
问题是:我的代码工作正常,它从一个到另一个发送和接收 UDP 数据包,反之亦然。但是在发送每个数据包之后,它会增加一个“Udp.remotePort”值(从“udp-reader”端查看)。它从 1024 到 ~32000 开始(并在达到最高值后重新开始)。我研究过 UDP,我知道第一个 0-1023 是为特定服务保留的。 80 http,21 ftp。但我认为它不应该在每次发送后增加。还是应该?
我没有粘贴代码,因为正如我所说,它可以正常工作。我只是想从您的经验中了解可能有什么问题。
我用来写数据包的句子是:
udp.beginPacket(IPAddress([ip address]), [port no]);
我正在使用的库:
UIPEthernet.h https://github.com/UIPEthernet/UIPEthernet for ENC28J60
以太网屏蔽的Ethernet.h
编辑:这是 UDP 发送方的代码 (ENC28J60)。基本上是库的示例代码,正如我所说的,它在通信方面可以正常工作。我只更改了 IP:192.168.1.50 是 UDP 发送方,192.168.1.51 是 UDP 目的地。
#include <UIPEthernet.h>
EthernetUDP udp;
unsigned long next;
void setup() {
Serial.begin(115200);
uint8_t mac[6] = {0x00,0x01,0x02,0x03,0x04,0x05};
Ethernet.begin(mac,IPAddress(192,168,1,51));
// Also i used: Ethernet.begin(mac,IPAddress(192,168,1,51), 5000);
// with the same result
next = millis()+2000;
}
void loop() {
int success;
int len = 0;
if (((signed long)(millis()-next))>0)
{
do
{
success = udp.beginPacket(IPAddress(192,168,1,50),5000);
Serial.print("beginPacket: ");
Serial.println(success ? "success" : "failed");
//beginPacket fails if remote ethaddr is unknown. In this case an
//arp-request is send out first and beginPacket succeeds as soon
//the arp-response is received.
}
while (!success && ((signed long)(millis()-next))<0);
if (!success )
goto stop;
success = udp.write("hello world&from&arduino");
Serial.print("bytes written: ");
Serial.println(success);
success = udp.endPacket();
Serial.print("endPacket: ");
Serial.println(success ? "success" : "failed");
do
{
//check for new udp-packet:
success = udp.parsePacket();
}
while (!success && ((signed long)(millis()-next))<0);
if (!success )
goto stop;
Serial.print("received: '");
do
{
int c = udp.read();
Serial.write(c);
len++;
}
while ((success = udp.available())>0);
Serial.print("', ");
Serial.print(len);
Serial.println(" bytes");
//finish reading this packet:
udp.flush();
stop:
udp.stop();
next = millis()+2000;
}
}
编辑 2:这是使用 SocketTest listening on port 5000, and after a packet received, the next one arrives with the remote port incremented on 1 each time 进行测试的捕获
【问题讨论】:
-
如果代码 100% 正常运行,您就没有问题。如果您有任何问题,您必须发布代码。
-
好的,我已经发布了代码。
标签: sockets networking arduino udp ethernet