Mega 2560 serial read and write problem

hi
I'm writing simple code but it seems that works wrong I don't know why ??

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

void loop() {
  while (Serial.available() > 0) {
    char s = Serial.read();
    Serial.println(s);
    if (s == 'a') {
      Serial.println("Hello World");
    }
    else {
      Serial.println("nothing");
    }
  }
}

1 Like

What do you want the code to do? What does the code do instead?

+1 for using code tags.

There will, be some suggestions on how to improve your serial communications forthcoming.

There is some serial basics write ups on this site, use search, that you'd want to read up on.

serial basics <<< a link, a link to serial basics thingy.

1 Like

You've set the line endings to NL and CR (in the serial monitor, leftmost dropdown list).
Switch that to None.

1 Like

1 Like

its work thank you

So there were two invisible control characters added at the end of each line,
you could also handle them in your code.

1 Like

Or you could use a real terminal program that transmits each character as it’s pressed.

CR not required.. it’s just another character.

1 Like

how is that ? you mean the code is worng ?
i have other problem when i change the type of serial.read() to int the number i get not like what i put exemple i put 1 and the result it 49 should i convert it to DEC or what

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

void loop() {
  while (Serial.available() > 0) {
    int s = Serial.read();
    Serial.println(s);
    if (s == 1) {
      Serial.println("Hello World");
    }
    else {
      Serial.println("nothing");
    }
  }
}

For single character commands, some measures to handle characters that are not commands
would be a better solution in my opinion.

The character '1' has the value 49 or 0x31. You could compare the int to a '1'.

BTW "nothing" and "not a '1'" is a big difference.

1 Like

yup you right but with arduino uno i dont face those problem is there a difference between them ??
for the " nothing " comment is just for testing haha
thank you very much for your time

Between what?

I guess you mean different expressions of a value like '1', 49, 0x31, 061, 0b110001 ?

Sometimes one variant results in code that is better to understand,
but basically all of them are equivalent, it makes no difference to the compiler.

1 Like

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.