simple echo program not working. ideas?

i've been beating my head against this for a few days now. the actual program i'm trying to write is quite a bit more complex, but the effect is reproducible with this:

void setup() {
  Serial.begin(115200l);
}

void loop() {
  if (Serial.available() == 0)
    return;
    
  while (Serial.available() > 0)
    Serial.print((char)Serial.read());
    
  Serial.println();
}

if i'm not a complete idiot, this should echo back everything sent to it. here's some sample output:

t
tYî
t
e
s
t
tY.÷

this was done through the serial monitor. i sent "t", and it worked. fine. i sent "tes", and the first character worked, the rest got messed up. i sent the word "test" one letter at a time, everything is great. i send the whole word - you see what happens. It's almost as if it's losing a bit or two. very strange.

tried this on two different arduino pro boards, on mac and pc (same computer, dual booted). any suggestions?

  Serial.begin(115200l);

Is that a 1 or an L on the end? It isn’t necessary, as the Serial.begin() method’s argument type is an unsigned long. If you do use a suffix, though, use a capital letter, to remove ambiguity (by us, not the compiler).

  if (Serial.available() == 0)
    return;

This is unnecessary. The while loop already deals with the situation where the is no serial data to read.

Do you have the same issues at lower baud rates?

it’s an L.

the second test actually is necessary. the final println() is outside the while loop, as a separator between inputs. if the first if isn’t there, it’ll just continuously print blank lines.

tried 9600, that did seem to resolve it. any idea as to why? in its final use, it will need to run at the 115200.

This speed is a bit high 115200l hopefully that is just a typo, with extra 1 stuck on the end.

I have cases where too many actions in one line just don't work, this may be one of them. Try splitting this up:

while (Serial.available() > 0) Serial.print((char)Serial.read());

into while (Serial.available() > 0) { incomingByte = Serial.read(); Serial.print (incoming); // with whatever formatting you want Serial.println(); } // or maybe its due to not having the brackets?

@crossroads - why do you say that it's too high?

tried your change at that speed, no impact (and yeah, that's an L on the end)

in its final use, it will need to run at the 115200.

What is the Arduino going to be talking to? Talking to a device that expects a baud rate of 115200 and talking to the serial monitor at that speed are two different things.

I missed the posts saying it was on 115,200. 1,115,201 would be on the fast side ;)

@PaulS - the issues started in a java app talking to it through the rxtx library that processing uses. similar effects.