This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

String tokenizing

I need to extract eight values from a string I'm receiving from my serial port. I have the following code:

unsigned char xdata *p_ch;
unsigned int  xdata ch = 0;

// Get command
   p_ch = strtok( com_buffer, "," );

// Get status
   while ( p_ch != NULL )
   {

//    Get string
      p_ch = strtok( NULL, "," );

//    Convert to float
      ad_value[ch] = atof( p_ch );
      ch++;

      if ( ch > 8 )
        break;

    } //__while ( p_ch != NULL )__

It works very intermittently. Can anyone suggest a better way to decode my serial string?

Thanks.

  • 1) the following code what code? code has comments.

    2) what is 'strtok'

    Erik

  • strtok() is a standard function. However, it is not a nice standard function since it modifies the input buffer, and hence most standards dislikes it a lot. strchr() is often a better choice - or sometimes the not so common strtok_r().

    Anyway - is your com buffer handled by an interrupt?
    You should not (!) try strtok() or most other parsing on a buffer that may be changed while the decoding is performed.

    Your cude is lousy! Where is the error handling? How do you know that strtok() finds a match before you call atof()? And how do you know that there is a number between the tokens?

    Code that contains error handling and that verifies the data will not just magically work intermittently. Real code would detect failures and would know where/why it fails. How do you even know when you are at the start of a line/command/block?

  • strtok() is a standard function. However, it is not a nice standard function
    probably the reason I did not recall it. I do not use "standard functions" a lot, they are bulky and slow because of their "universality".

    Real code would detect failures

    THAT can not be said often enough!!

    Erik

  • You're right. There is no error handling what so ever. It's just some quick code I threw together as an example.

    I know the data coming across because it's the only other data on the bus.

  • If it is just some code you "threw together", then you should wait until your code has some form of error handling before asking why it only works intermittently. The error handling will not only stop your code from processing bad data - it will also help you to find bugs in your code or incorrect assumptions about your data.

  • It works very intermittently.

    That's no way to describe a problem. It's not even beginning to tell anyone what actually happens.

    So here we have code that makes no effort at catching problems, and its author making no effort either. How do you think that could possibly lead to anybody ever figuring out what's going wrong?