1

Hello and thanks for taking the time to look at this.

I'm experimenting with Arduino by reading into a character array over serial. This will ultimately be used for communicating with a raspberry pi and splitting a received string such as: '100,200,300' into: Var1 = 100, Var2 = 200, Var3 = 300 etc.

Having looked around the various forums, I tried to write my own serial to string function as follows:

String message;
int buflen = 12;
int bytesread = 0;


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


void loop() 
{
  if (Serial.available() > 0)
  {
  message = ReadStringFromSerial();
  Serial.print("Read message is: ");
  Serial.println(message);
  }
}

String ReadStringFromSerial()
{
   char serialarray[buflen];
   bytesread = Serial.readBytesUntil('\0', serialarray, buflen);
   Serial.print("Array: ");
   Serial.println(serialarray);
   Serial.print("Bytes read: ");
   Serial.println(bytesread); 
   String returnedmessage = String(serialarray);
   return returnedmessage;  
}

However, when repeatedly typing 'test' into the serial monitor, I get the following:

Array: TestA
Bytes read: 4
Read message is: TestA
Array: TestXXX
Bytes read: 4
Read message is: TestXXX
Array: TestXXXXó
Bytes read: 4
Read message is: TestXXXXó

I would like to know where the extra characters are coming from as I'm a little confused. Also, does the serial monitor add any extra characters such as a null character '\0' or does it just send back 'test' rather than 'test\0'

Many thanks for your help,

Robin

1 Answer 1

1

When you declare your serialarray you are just setting a pointer to a memory location which may contain any kind of data that was previously stored there.

Then you are reading data from serial until '\0' (not sure if it is not included or is actually never found since you are not typing it in the monitor).

In any case the string you are creating is not terminated.

You could do this to terminate your string:

bytesread = Serial.readBytesUntil('\0', serialarray, buflen);
serialarray[bytesread] = '\0';

And all the extra characters will disappear...

Sign up to request clarification or add additional context in comments.

1 Comment

That's fantastic, thank you. I will implement this and report back!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.