2017-06-26 68 views
-1

我正在处理两个arduinos的代码,一个使用以太网屏蔽,另一个使用ENC28J60以太网模块。我不是arduino的新手,也不是智慧/专家。但我是一个完整的 - 而且不是UDP通信的新手。数据包发送后UDP端口arduino增量

下面是问题:我的代码工作正常,它发送和接收从一个到另一个的UDP数据包,反之亦然。但是在发送每个数据包之后,它将增加一个“Udp.remotePort”值(从“udp-reader”端查看)。它从1024开始到32000(在达到最高值后重新开始)。我已经研究过UDP,并且我知道第一个0-1023是为特定服务p.e保留的。 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

+1

如果代码正常工作,那么您没有任何问题。如果你有问题,你必须发布代码。 – EJP

+0

好的,我发布了代码。 – charly989

回答

1

您必须创建每个数据包发送一个新的UDP套接字捕获。不要这样做。在应用程序的生命周期中使用同一个。

+0

我不知道如何避免这种情况,我做错了什么? – charly989

+0

@ charly989,每次在应用程序生命期间写入文件时,是否重新打开文件?不,那会很愚蠢和缓慢。在应用程序设置期间打开套接字,在应用程序循环中使用它,并在应用程序完成时关闭它。 –

+0

好吧,好的比喻我明白你的观点(我会运用它)。然而,我仍然不知道为什么在这个特定的代码中,每发送一个数据包后端口都会增加1。请检查上传的img。 (编辑2)。 – charly989