Search code examples
arduinotouchsensorsandroid-sensorsrelay

Relay turn on by any of 3 touch sensors


I have a relay and i want to turn on the light with it and i have 2 touch sensors but with this code i can only turn it on with 1 how can i make it work? The third is a switch but it should still work the same. I've tried and it worked with a different code. But that code was for a servo and not a relay.

int touchPin   = 4;
int touchPin2   = 6;   // Arduino pin connected to touch sensor's pin
int touchPin3   = 7 ;
int relayPin = 9;

int val = 0;
int lightON = 0;
int touched = 0;

void setup() {
  Serial.begin(9600);
  pinMode(touchPin, INPUT); 
    pinMode(touchPin2, INPUT);
      pinMode(touchPin3, INPUT);
  pinMode(relayPin, OUTPUT);

}

void loop() {

  val = digitalRead(touchPin);
    val = digitalRead(touchPin2);
      val = digitalRead(touchPin3);

  if(val == HIGH && lightON == LOW){

    touched = 1-touched;
    delay(100);
  }    

  lightON = val;

      if(touched == HIGH){
        Serial.println("Light ON");
        digitalWrite(relayPin, LOW); 
       
      }else{
        Serial.println("Light OFF");
        digitalWrite(relayPin, HIGH);
   
      }     

  delay(100);
}

Solution

  • You need to handle all three digital inputs together. In your code

    val = digitalRead(touchPin);
    val = digitalRead(touchPin2);
    val = digitalRead(touchPin3);
    

    you are overwriting the first two read values by the last one. You should combine them or handle all three separately. Combining three reads to one value that will be HIGH if any is HIGH:

    val = digitalRead(touchPin) || digitalRead(touchPin2) || digitalRead(touchPin3);
    

    Separately:

    int val  = digitalRead(touchPin);
    int val2 = digitalRead(touchPin2);
    int val3 = digitalRead(touchPin3);
    
    if ((val == HIGH || val2 == HIGH || val3 == HIGH) && lightON == LOW) {