Go Down

Topic: Serial Event example NOT COMPLETE (Read 529 times) previous topic - next topic

AndreaDenaro

Hi guys,

on https://www.arduino.cc/en/Tutorial/SerialEvent example code, a line of code should be added in the serialEvent() routine:

void serialEvent() {
  while (Serial.available()) {
    // get the new byte:
    char inChar = (char)Serial.read();
    // add it to the inputString:
    inputString += inChar;
    // if the incoming character is a newline, set a flag so the main loop can
    // do something about it:
    if (inChar == '\n') {
      stringComplete = true;
      inputString = inputString.substring(0,inputString.length()-2); //******** new line ********
    }
  }
}

The new line give back the exatly string received, and nothing more.

AWOL

If you don't want the newline, don't put it in the String.
Better still, don't use String at all.
"Pete, it's a fool looks for logic in the chambers of the human heart." Ulysses Everett McGill.
Do not send technical questions via personal messaging - they will be ignored.
I speak for myself, not Arduino.

AndreaDenaro

In the original example is tested:

if (inChar == '\ n') ....

so, i think is correct what i said

pert

@AndreaDenaro please use code tags (</> button on the toolbar) when you post code or warning/error messages. The reason is that the forum software can interpret parts of your code as markup, leading to confusion, wasted time, and a reduced chance for you to get help with your problem. This will also make it easier to read your code and to copy it to the IDE or editor. If your browser doesn't show the posting toolbar then you can just manually add the code tags:
[code] // your code is here [/code]
Using code tags and other important information is explained in the How to use this forum post. Please read it.

The example sketches are meant to be very simple demonstrations of a concept. Your suggested addition introduces some complex code. The only thing that might be considered a problem with the current code is that  it prints a blank line to the Serial Monitor after each string. If this was really an issue that could be solved in a much more simple and efficient way by merely changing line 34 from:
Code: [Select]
Serial.println(inputString);
to:
Code: [Select]
Serial.print(inputString);

westfw

We could argue for months about whether the newline should be considered "part of the string received."
But WHY "-2"??  Are you assuming that any line terminated by a newline is terminated by "\r\n"?  That's not a safe assumption!

AWOL

In the original example is tested:

if (inChar == '\ n') ....

so, i think is correct what i said
Of course it is tested, but it has already been added to the String.
"Pete, it's a fool looks for logic in the chambers of the human heart." Ulysses Everett McGill.
Do not send technical questions via personal messaging - they will be ignored.
I speak for myself, not Arduino.

Go Up