Digital Input using a button doesn't work properly when using it to control a relay I'm trying to control a relay both via Bluetooth and using a switch. The problem is that, when the LED is off, I can turn it on with the switch but then if I turn off the switch the relay will stay on. Is there something wrong with my code? Thanks in advance. The switch is installed as follows: 


Here is my code: Switch is connected to pin 3 and the relay is connected to pin 2.


//bluetooth hc-06
int ledPin = 2; // usamos un pin de salida al LED
int state = 0; // Variable lectrura serial
int interruptor=3;

void setup() {
    pinMode(ledPin, OUTPUT);   //Declara pin de Salida
    pinMode(interruptor, INPUT);
    digitalWrite(ledPin, LOW); //Normalmente Apagado
    Serial1.begin(9600);
    }

void loop() {
  int valor=digitalRead(interruptor);

  if(Serial1.available() &gt; 0){
       state = Serial1.read();
  } // esta parte del código es para solo 1 Carácter o Unidad. 


 if (state == '0'&amp;&amp; valor== LOW) {
    digitalWrite(ledPin, LOW);
    Serial1.println("LED: off");
 }


 else
 if (state == '1' || valor== HIGH) {
     digitalWrite(ledPin, HIGH);
     Serial1.println("LED: on");
 }


}


New code:

//bluetooth hc-06
int ledPin = 2; // usamos un pin de salida al LED
int state = 1; // Variable lectrura serial
int interruptor=3;

void setup() {
    pinMode(ledPin, OUTPUT);   //Declara pin de Salida
    pinMode(interruptor, INPUT);
    digitalWrite(ledPin, LOW); //Normalmente Apagado
    Serial1.begin(9600);
    }

void loop() {
  int valor=digitalRead(interruptor);
 //si el modulo ha mandado dato, guardarlo en estado.

  if(Serial1.available() &gt; 0){
       state = Serial1.read();
  } // esta parte del código es para solo 1 Carácter o Unidad. 

 // si el estado es 0 ese sería Apagado “OFF”
 if (valor== LOW) {
    digitalWrite(ledPin, LOW);
    Serial1.println("LED: off");
 }

 // de lo contrario si el estado es 1 ese sería Encendido “ON”
 else
 if (valor== HIGH) {
     if (state== 1){  
     digitalWrite(ledPin, HIGH);
     Serial1.println("LED: on");
     }
     else if (state== 0){
     digitalWrite(ledPin, LOW);
     Serial1.println("LED: off");

     }
 }


}
You have to invalidate the ‘state’ variable when Serial is not available, otherwise you will produce strange behaviours.

if(Serial1.available() > 0){
       state = Serial1.read();
  } else {
       state =-1; // not valid
    }

Also, you have to check ‘1’ and ‘0’ characters and not 1 and 0 values. ‘if (state == ‘1’)..’