Why my if statment not working as intended?

hi,
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:
  Serial.begin(9600);
  pinMode(led, OUTPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
  while(Serial.available()){
    static char message[max_char];
    static int pos = 0;
    char input = Serial.read();
    if(input != '\n'){
      message[pos] = input;
      pos++;
    }
    else{
      message[pos] = '\0';
      Serial.println(String("Your message: ") + message);
      pos = 0;
    }
    if(message == "on"){
      digitalWrite(led,HIGH);
      
    }
    else if(message == "off"){
      digitalWrite(led,LOW);
    }
    else{
      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