PlatformIO Community

Character array to string

I receive a string from the serial port using:

int len = Serial.readBytesUntil( '\n', inBuffer, INBUFFER_LENGTH - 1 );

I then try and convert it to a String with:

String response = String( inBuffer );

However, when I print the string I get corrupt data.
I then changed the code to output each character in inBuffer:

for ( int i = 0 ; i < len ; i++ )


            Serial.printf( "%2u:%c %02X\r\n", i, inBuffer[ i ], inBuffer[ i ] );


        String response = String( inBuffer );

        Serial.println( response );

What I see when I type *IDN? and hit return (LF) I get:

0:* 2A
1:I 49
2:D 44
3:N 4E
4:? 3F

You can see that last entry which is when I call Serial.println( response ); is corrupt.

What am I doing wrong?


Never mind, I just looked at the source for readBytesUntil and it does not actually null terminate the string when it finds the terminator :frowning: