Go Down

Topic: UDP packet parsing, Ethercard library (ENC28J60) (Read 1 time) previous topic - next topic

Hello,
I'm converting some code I've written for the WZ5100 to ENC28J60. Ran into some trouble reading a UDP packet and parsing the data within. In this example, I read the first two bytes of the packet as "S" "0" then the next byte is a value (say a delay time, or pwm value, or something useful).

first example here using WZ5100 works fine:

Code: [Select]

Udp.read(packetBuffer,UDP_TX_PACKET_MAX_SIZE);

if(packetBuffer[0] == 's' && packetBuffer[1] == '0')        
    {
      packetBuffer[0] = ' '; //S
  packetBuffer[1] = ' ';

      int val = (atoi(packetBuffer));
 
  digitalWrite(2, HIGH);
  delay(val);  // the delay time was passed from the UDP packet
  digitalWrite(2, LOW);
    }


But this next code (ethercard) does not work - when I do "atoi" I just get "0"

Code: [Select]


setup(){
//some other setup info here...
//...

ether.udpServerListenOnPort(&udpSerialPrint, 30311);  // callback to function

loop(){
ether.packetLoop(ether.packetReceive()); 

}

void udpSerialPrint(word port, byte ip[4], const char *data, word len) {
  IPAddress src(ip[0], ip[1], ip[2], ip[3]);
  Serial.println(src);
  Serial.println(port);
  Serial.println(data);
  Serial.println(len);

if(data[0] == 's' && data[1] == '0')        
    {
    //  packetBuffer[0] = ' ';
//  packetBuffer[1] = ' ';

  int onTime = atoi(data);  //<----- trying the same atoi here
      Serial.println(onTime);  // added this for debug

  digitalWrite(2, HIGH);
  delay(onTime);
  digitalWrite(2, LOW);

    }


what is being done differently with "packetBuffer"  than with "data"?

thanks in advance

PaulS

Code: [Select]
if(data[0] == 's' && data[1] == '0')        
    {
    //  packetBuffer[0] = ' ';
//  packetBuffer[1] = ' ';

  int onTime = atoi(data);  //<----- trying the same atoi here

If data[ 0 ] is an 's', of course atoi(data) is going to return 0. 's' is not an integer digit.

In the other code, you set packetBuffer[ 0 ] and packetBuffer[ 1 ] to spaces. Why are you not doing that to data?

Refering to http://www.cplusplus.com/reference/cstdlib/atoi/ it seems that your string is somehow corrupted. The last paragraph explains exactly your problem:
Quote
If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed and zero is returned.


So you should have a look what exactly is stored in your "data" - variable.
KaiHeinz Software - http://kaiheinz.de

Go Up