Why my if statment not working as intended?

I am trying to use serial.read() function. But when I write "On", it goes to else statment! I know that Serial.read() function can only read 1 byte, but I created an array to store the byte.
Here's the code:

const int max_char = 12;
const int led = 10;

void setup() {
  // put your setup code here, to run once:
  pinMode(led, OUTPUT);

void loop() {
  // put your main code here, to run repeatedly:
    static char message[max_char];
    static int pos = 0;
    char input = Serial.read();
    if(input != '\n'){
      message[pos] = input;
      message[pos] = '\0';
      Serial.println(String("Your message: ") + message);
      pos = 0;
    if(message == "on"){
    else if(message == "off"){
      Serial.println("only on/off !");

You checked for '\n', but what about '\r'?

Also "On" is not the same as "on"

what means \r?

'\r' is carriage-return.

Try using strcmp instead of "=="

1 Like

i wrote on

but i the post I made a mistake. I mean on not On

No, in your original post, you wrote "On"

can you pls tell me how to use strcmp and what it means

strcmp is used to compare C strings.
It returns zero if the two strings are identical.

how can i use strcmp?

if (strcmp (string0, string1) == 0) {
// The two strings are identical
1 Like

thank you, now my code works!
one question: where did you learn c programming?

I was thrown in at the deep-end, writing diagnostics for a hybrid 68k/bit-slice image processing engine.

1 Like

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