Search code examples
parsingarduinoudpbufferethernet

Arduino parses UDP packets through Ethernet with gibberish in it


Arduino Yun (with built-in Ethernet) is connected to a PC (through Ethernet) which is connected (through WiFi) to my router. Is set to receive UDP packets from another PC (on the same network). That PC uses netcat to send those packets.

Arduino Yun prints the received packets, but it also prints some gibberish.

I'm pretty sure it has something to do with the remaining data on the buffer from previous transmissions. This is what I send: enter image description here

Then I write "a" and press enter (also from netcat), and Arduino gets this: enter image description here

And this is my code:

char udp_buffer[UDP_TX_PACKET_MAX_SIZE];

void setup() {
  Bridge.begin();       
  Udp.begin(9911); 
  Serial.begin(9600);
  if (!rf95.init())
    Serial.println("init failed");     
rf95.setTxPower(20, false);

IPAddress IP(192, 168, 1, 10);

}

void loop() {
   int udp_received = Udp.parsePacket();
   if (udp_received) {
      Udp.read(udp_buffer, UDP_TX_PACKET_MAX_SIZE);
      Serial.println(udp_buffer);



  }
}

Solution

  • You send only 5 or 6 characters "test\r\n". the rest is random memory content.

    The return value of parsePacket should be the count of received characters, but the implementation in BridgeUdp is wrong and returns always 1 on success.

    You you can use BridgeUdp.available() to get the count.

    void loop() {
      if (Udp.parsePacket()) {
        int udp_received = Udp.available();
        char udp_buffer[udp_received + 1];
        Udp.read(udp_buffer, udp_received);
        udp_buffer[udp_received] = '\0';
        Serial.println(udp_buffer);
      }
    }