[Solved] Weird sscanf(?) problem. Explain this!

Hello, so I was doing some tests to make a command processor, here is the code:

void setup ()
{
  Serial.begin(9600);
}

void loop()
{
  if ( Serial.available () > 0 ) 
  {
    static char input[16];
    static uint8_t i;
    char c = Serial.read ();

    if ( c != '\r' && i < 15)
      input[i++] = c;

    else
    {
      input[i] = '\0';
      i = 0;

      char yeah[] = "azerty";
      if ( !strcmp( input, yeah ) )
        Serial.println("hello");
        
      char cmd[32];
      uint8_t var;

      if ( sscanf( input, "%s %d", cmd, &var ) == 2 )
      {
        char output[32];
        sprintf( output, "cmd:%s var:%d", cmd, var );
        Serial.println( output );
      }
    }
  }
}

This code does work. For example you type “abc 123” then Enter in the serial monitor window, the code output as expected:

cmd:abc var:123

However, if I remove those 3 -useless- lines:

char yeah[] = "azerty";
if ( !strcmp( input, yeah ) )
  Serial.println("hello");

Or, if I change them to:

if ( !strcmp( input, "azerty" ) )
  Serial.println("hello");

Or even…

char yeah[] = "azerty";
if ( !strcmp( input, yeah ) ) { }

… Or whatever I do to those lines, then the code doesn’t fully work and only output:

cmd: var:123

(it’s missing the cmd parameter).

Can you explain this strange behavior?

Thanks :slight_smile:

Change this...

      uint8_t var;

...to this...

      int var;
      uint8_t var;

      if ( sscanf( input, "%s %d", cmd, &var ) == 2 )

Isn't %d an int, not a byte?

Like Coding Badly said.

Thank you, now it worked! But can you bother to explain the weird behavior, I'm interested knowing why it happened :)

guix: Thank you, now it worked! But can you bother to explain the weird behavior, I'm interested knowing why it happened :)

scanf stored two bytes where there was only space for one, ie. something else got corrupted in memory.

Ok thank you, too bad there isn't a sscanf specifier for uint8_t values...I've read about the macro SCNu8 but not implemented in avr gcc.

Edit I've just tried with "%hhu" and it worked! hurra!

see also - http://www.nongnu.org/avr-libc/user-manual/group__avr__stdio.html - (you might need a lot of scrolling)