0

I am not actually using ad arduino but an atmel chip. but my question is c microprocessor related

I am reading an uart which returns data in the form uint8_t [100] I can print the return just fine, the return is "OK"

but when I try to use strcmp(read, "OK") I do not get the expected value, I get a mismatch ( strcmp returns 13, not 0)

uint8_t  sigfox_rd_buf[100] = {0};
uint8_t sig_rd = 0;

io_sigfox->read(io_sigfox,&sig_rd, 1);
while(sig_rd != 10) // read until end char
 {
     sigfox_rd_buf[i] = sig_rd;
     i++;
     io_sigfox->read(io_sigfox,&sig_rd, 1);
 }
 if(strcmp((char *)sigfox_rd_buf,"OK") == 0 )
 {
  do_something()
 }
 else
{
complain();
}

and I always end up in complain for some reason.. please help!! :)

3
  • 1
    Does 13 not give it away? Jun 25 '16 at 23:18
  • An unexpected carriage return could indeed be an issue, though it's an implementation quirk if an actual character is returned by strcmp(). But the code also fails to terminate the string in the receive buffer - it may work if the startup code zero initializes memory and it has not been touched since but subsequently it may run away comparing residual garbage until finally finding a zero byte. Jun 26 '16 at 2:30
  • Bahh stupid copy paste error... was taken for another uart read sequence where the message ends with a line feed and a carriage return! somehow I stared my self blind..
    – rasmus
    Jun 26 '16 at 10:22
1

When using strcmp(), strings should be terminated with a NULL character. Which, by the way, is a zero. Your code should work as is if you replace the Line Feed character (10 or 0x0a) with a NULL (0 or 0x00). That is assuming the string you are getting back is 0x4f, 0x4b & 0x0a. Or you could play it safe and replace strcmp with strncmp. Then explicitly state the number of characters to compare:

if(strncmp((char *)sigfox_rd_buf,"OK",2) == 0 )
2
  • In general, yes, but we don't actually know that the data providing function will return nulls at this point, or if how much data we over or under read will leave the next run in a bad starting condition. Sigfox perhaps implies packets more than streams, but the interface being used looks at least momentarily stream-like. Jun 26 '16 at 17:07
  • Ok, I change the wording so as to explicitly state strcmp() string arguments should be terminated by NULL.
    – st2000
    Jun 26 '16 at 17:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.