IF and &&

Hi:

I have the following code:

int a = 0;

void setup(){
 
 Serial.begin(9600); 
 pinMode(9, OUTPUT);
 
}

void loop(){
 
 byte val;
  if(Serial.available()){
    val = Serial.read();
    switch (val) { 
    case 'U': a += 1; break;   
    case 'D': a -= 1; break;
    }} 
  
 if((a >= 5)&&(a <= 10)){
 digitalWrite(9, HIGH);} 
 
 Serial.println(a);
  
}

The intention of this code is that when "a" is between 5 and 10 (including 5 and 10) an LED connected to pin9 is lit, but only within this domain. The problem is when the number 5 is reached and the led is turned on, if "a" goes below 5 or above 10, the LED remains lit!

What sould be the correct sintaxis to achieve such result?

Look up the else statement, then use it with a line that turns off the led:
digitalWrite(9, LOW);}

And here's a hint.... you already use serial.print to show what val is and that's great. But when you have an "if" it can be very helpful to put a serial print inside the "if" to say something like "I'm in the if". That way, you would have seen that your "if" is actually working, but since you never switch the led off- as pointed out by LarryD- you probably thought your code was taking a path through the "if" when it wasn't.

And if you have an if with loads of elses, you can put a "I'm in the ....." in each one, to keep track of where the flow actually goes.

If you want to turn it off, then you need to add some code to turn it off.

Thanks for point out the fact that I wasnt giving any instructions to turn off the LED. So it was turned on the first time and if the "if" instruction was true, another HIGH value was overwritten on the pin9.

and if the "if" instruction was true, another HIGH value was overwritten on the pin9.

Yes. Pins latch. You don't need to keep telling them the value you want them to have.