Digital output not consistent

I've been trying to control some LED diodes via digital pins but the code is acting weird. I hope there's some mistake that I'm not seeing.
Here's the code:

int led=7;
void setup() {
    Serial.begin(9600);
    pinMode(led, OUTPUT);
}
int y=0;
void loop() {
  if (Serial.available()){
    int y=Serial.read();}
  if (y==1){
    digitalWrite(led,HIGH);}
  else digitalWrite(led,LOW);
}

On the other hand, here's a similar code that works perfectl:

int led=7;
void setup() {
    Serial.begin(9600);
    pinMode(led, OUTPUT);
}
int y=0;
void loop() {
  digitalWrite(led,HIGH);  //works
  delay(400);
  digitalWrite(led,LOW);   //works
  delay(400);
  if (Serial.available()){
    Serial.write(Serial.read());}    //works
}

Look at the scope of the y variable in the first example, particularly the y inside the Serial.available condition

It works fine, I've forgotten to copy the line: Serial.write(y);.
It reads the input successfully, and prints it back to the Serial monitor. So it's not the y I suppose.

  if (Serial.available()){
    int y=Serial.read();}

You can suppose all you like, but I don't see the point in assigning a value to a variable that's going to go out of scope in a few hundred nanaoseconds.

I am sorry, but I don't think I understand you. Can you suggest a solution?

Sure - lose the "int", then you'll use the other y.

Did that, nothing has changed.

How are you sending the binary 1 via serial?
Did you mean if (y=='1'){?

When you type '1' on you keyboard that gives you the char '1' not the number 1, note how ther are written.

Mark

I am writing in the Serial Monitor bar via keyboard. I don't think the if clause there is making any problem, because it works alright just like that reading integers.

I don't understand your reply.
Can you post your code, your expectations and observations?

My intention is to type “1” in the Serial monitor and get a LED diode on pin 7 to light up, or anything else to turn it off.

Post your code, your expectations and your observations.

I've actually found the problem. While pressing EOL (Enter) it gives a few values. For example "1" + Enter will eventually send: 1 + \n + \r. Just need to trim them. It immediately changed the value after pressing Enter. Thanks for the help.

Hi,

void loop() {
  if (Serial.available()){
    int y=Serial.read();}
  if (y==1){
    digitalWrite(led,HIGH);}
  else digitalWrite(led,LOW);
}

There are supposed to be { and } used after your else .

I'm surprised it Auto Format and Compiled like that, but it did.

Tom..... :slight_smile: