Sscanf function in arduino code

Could somebody please put me out of my misery..
I use the following code:-

Serial.println("Start example");
char buffer[16];
sscanf(buffer, "1234567890");
Serial.println(buffer);
Serial.println("End Example");

The "1234567890" is not sent.
What am I doing wrong?

It is not clear what you are trying to do, but the code you posted won't do anything useful.

Take a look at some tutorials on how to use sscanf(). Randomly chosen example:

Did you mean to copy the string, using strcpy()?


char buffer[16];
strcpy(buffer, "1234567890");
Serial.println(buffer);
1 Like

Serial.begin !

Well, no, it wouldn't be sent. That's not how you use sscanf. sscanf reads formatted data from a string and stores it into variables according to a format string.

What this what you were trying to do?

void setup() {
   char buf[] = "1234567890";
   unsigned long result;

   Serial.begin(115200);
   Serial.println("Start example");
   sscanf(buf, "%lu", &result);
   Serial.println(result);
   Serial.println("End Example");
}

void loop() {
}

Or were you simply trying to copy "1234567890" into buf, as @jremington showed?

look this over


const char *prompt = "enter cmd: ";

void
loop (void)
{
    if (Serial.available ())  {
        char buf [90];
        int  n = Serial.readBytesUntil ('\n', buf, sizeof(buf)-1);
        buf [n] = '\0';

        int  val;
        char cmd [10];
        sscanf (buf, "%d %s", & val, cmd);

        Serial.print ("cmd ");
        Serial.print (cmd);
        Serial.print (", val ");
        Serial.println (val);

        Serial.print (prompt);
    }
}

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

the C Programming Language pg 140

Thanks everybody the example I gave was not good.
What I'm actually trying to do is output to a parallel port (8 pins) on an ESP32 text that will contain variables.
I wrote a function to output text on that parallel port and it works fine.
Now I want to output text containing variables.
I was just using Serial.println() to simplify the question. Now realize it was an incorrect example.

Rephrasing the question how do I do something like:-

char buffer[64];
sscanf(buffer,"text string" + a variable number + more "text string");

Thanks in advance
John

Clearly, you have no idea what the function sscanf() actually does, and we still don't know what you are trying to do.

sscanf(buffer,"text string" + a variable number + more "text string");

sprintf() can produce a formatted string like the above

int val = 1234;
char buffer[40];
sprintf(buffer, "text string %d more text string", val);
Serial.println(buffer);  //prints: text string 1234 more text string

Thanks that's it!!!
John

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.