4

this is my first question in this forum.

I need to receive a string from the Arduino serial monitor and display it when the communication is over. I have a similar problem like the one discussed in this thread:

https://electronics.stackexchange.com/questions/45543/how-do-i-receive-an-entire-string-as-opposed-to-1-character-at-a-time-on-the-ard

Only I'm using the Arduino serial monitor instead of a RaspberryPi to send strings so I can't program the sender to attach an identifier like '\n' at the end of the string.

char inData[20];
char inChar=-1;
byte index = 0;
while (Serial.available() > 0){
 ending[1]=ending[1]+1;
 if(index < 19){
 inChar = Serial.read();
 inData[index] = inChar;
 index++;
 inData[index] = '0円';
 Serial.flush(); 
 }
 Serial.print(inData);Serial.print("\t");Serial.println();
}

What I receive in the console looks like this:

M
Me 
Mes 
Mess 
Messa 
Messag
Message

I need to display only the final string

Message

The code has to know when the incoming string ended and then display it once.

I'd really appreciate any help I can get.

asked Nov 6, 2016 at 14:06
1
  • 1
    You have two options. The most reliable is to decide that a particular character will serve as an end-of-message indicator. \n is a common choice, but you can choose whatever you are not going to use in the message itself. The other option is to have a timeout: if no further characters have been received for XXX ms, then assume the message is complete. Commented Nov 6, 2016 at 17:42

1 Answer 1

2

If you really want a string. Try using Serial.readString(). It will return the full string.

The code could look like this:

if(Serial.available() > 0)
{
 String message = Serial.readString();
 Serial.println(message);
}
answered Nov 6, 2016 at 18:37
2
  • 1
    It is worth noting that Stream::readString() works with a timeout, which is 1 second by default, but can be changed with setTimeout(). Commented Nov 6, 2016 at 19:23
  • Thank you, that's exactly what I needed. Now the output in the serial monitor is the entire text input. First post, first issue solved. I'm really grateful. Commented Nov 7, 2016 at 1:20

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.