<stdlib.h> Can it parse communication and obtain a single letter?

I am receiving a communication from another arduino composed from a number, a letter and termination. Here is how I send it.

sprintf_P(ToSend, PSTR("%04d, %c, %02d\n"), 14, 'R', '\n');
Serial3.write (ToSend);

On the receiving side I got the code below. Works great, except I am not getting the R character, I always get an i. GO figure. Please help,

void recvWithEndMarker() {
    static byte ndx = 0;
    char endMarker = '\n';
    char rc;
    
    while (Serial3.available() > 0 && newData == false) {
        rc = Serial3.read();

        if (rc != endMarker) {
            receivedChars[ndx] = rc;
            ndx++;
            if (ndx >= numChars) {
                ndx = numChars - 1;
            }
        }
        else {
            receivedChars[ndx] = '\0'; // terminate the string
            ndx = 0;
            newData = true;
        }
    }
}

void showNewData() 
{int X1_Latest=0; 
char X2_Latest = 'x';
    if (newData == true) {
       
    char* ptr;
    ptr = strtok(receivedChars, ",");
    X1_Latest = atoi(ptr);
    ptr = strtok(NULL, ",");
    X2_Latest = ptr;
    
      Serial.print("  X1 Latest: ");
     Serial.print(X1_Latest);
     Serial.print("  X2 Latest: ");
      Serial.println(X2_Latest);
 
  
     //Serial.println(receivedChars);
        newData = false;
    }
}

Thank you brother.
I tried and now I get no char at all

X1 Latest: 0 X2 Latest:
X1 Latest: -15 X2 Latest:

That worked, thanks a lot. I got to learn data pointers...

This is looks like an error.

The formatting string is expecting the parameters to be a number, a character and another number. But you give it a number, a character and another character. You will get some other, potentially unpredictable, number, after the 'R' character. Does the ToSend array have enough space to hold that? If not, memory may get unexpectedly overwritten, possibly causing some very strange errors.

why not use readBytesUntil() and sscanf()


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

        int  val0;
        int  val1;
        char c0;
        sscanf (buf, "%d, %c, %d", &val0, &c0, &val1);

        Serial.println (val0);
        Serial.println (val1);
        Serial.println (c0);
        Serial.println ();
    }
}

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

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