I know there are some other posts about serial and strings, but I can't find the problem in my code in any of them. I am trying to make the my Arduino One get a string from the serial and store it as is. For some reason beyond my understanding, the first part of the string gets cut into chars, and the rest in random chunks. Does anyone know why this happens?
This is the code:
char value;
String inString = "";
void setup() {
Serial.begin(9600); // open the serial port at 9600 bps:
Serial.write("Power On\n\n");
}
void loop()
{
while (Serial.available() > 0)
{
value = Serial.read();
inString = inString + value;
}
if (inString !="")
{
Serial.print("received: ");
Serial.println(inString);
inString = "";
}
}
And this is the result in the serial monitor when I run it and input "random string gets cut in pieces":
Power On
received: r
received: a
received: n
received: d
received: o
received: m
received: string
received: gets cut in pieces
Consider the speed at which characters are sent and received.
In your case, one character takes over 1ms to transmit.
In that time, your processor could execute 16000 instructions.
The other posters have pointed out some errors/improvements. In addition, get rid of the String class. Note that if you use the keyword String in your code, the compiler is forced to call in the String class, which can bloat your code unnecessarily. Replace the String with a simple char array. Compiling your code required 3922 bytes while the alternative below uses 2228 bytes. Most of the difference is the bloat from the String class.
char inMessage[25]; // Assume max chars expected is 24, with room for null terminator
void setup() {
Serial.begin(115200); // open the serial port at 115200 bps:
Serial.println("Power On");
}
void loop()
{
int bytesRead;
inMessage[0] = '\0'; // Clear the array
while (Serial.available() > 0) {
bytesRead = Serial.readBytesUntil('\n', inMessage, 24); // Read until a newline...
inMessage[bytesRead] = '\0'; // Add string terminator
}
if (inMessage[0] != '\0') { // If something sent, show it...
Serial.print("received: ");
Serial.println(inMessage);
}
}
Also, using the Serial method readBytesUntil() simplifies the input code.