sscanf question

I’m sure I am missing something with regards to data types but I can’t find an answer. I am trying to read a hex color code from the serial port and convert it to R, G, B values to send to a full color LED. The LED sort of inverts the color code where 255 = darkest and 0 = brightest.

Either way, when I sscanf a string like “ff0000” to a unsigned long (or any value) sscanf shaves off the high byte (ff in the example above) and can only seem to scan 32-bit values.

unsigned long value = 0L;
char buffer[8];
int index = 0;

void loop() 
{
    if(Serial.available() > 0)
    {
        char ch = Serial.read();
        Serial.print(ch);
        
        if(ch == '\r')
        {
            buffer[index] = 0;
            sscanf(buffer, "%x", &value);
            
            byte r = 255 - ((value & 0xff0000L) >> 16);
            byte g = 255 - ((value & 0x00ff00L) >> 8);
            byte b = 255 - (value & 0x0000ffL);

            analogWrite(redPin, r);
            analogWrite(greenPin, g);
            analogWrite(bluePin, b);
            
            index = 0;
        }
        else if(index < 6)
        {
            buffer[index++] = ch;
        }
    }
}

Unsigned int only holds 32-bit values.

Sorry, I updated the example to reflect. Even with an unsigned long the top byte seems to get shaved off.

You need to tell sscanf to output a long. eg.

unsigned long value = 0L;
char buffer[10] = "ABCDEF12";

void setup() 
{
  Serial.begin (115200);

  sscanf(buffer, "%lx", &value);

  Serial.println ();
  Serial.println (value);
  
}

void loop () {}

Output:

2882400018

That worked. Thanks Nick!