Search code examples
arduinotouchsensors

Make relay be turned on by any of 3 touch sensors


I have a relay and i want to turn on the light with it. 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.

int touchPin = 2;
int relayPin = 3;

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

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

}

void loop() {

  val = digitalRead(touchPin);

  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

  • I suggest reading up on Arduino programming so that you can fully understand what is happening in someone else's program and then modify it to suit. There are tons of resources online just waiting for you :)

    This is how I would write the program:

     `/*
      * As I understand the relay is to turn on a light, 
      * should either of the touch sensors be triggered
      */
    
      const int touchPin_1 = 2;
      const int touchPin_2 = 3;
      const int relayPin = 4;
    
      bool isLightOn = false;
    
      void setup() {
          pinMode(touchPin_1, INPUT);
          pinMode(touchPin_2, INPUT);
          pinMode(relayPin, OUTPUT);
    
          Serial.begin(9600);
      }
    
      void loop() {
    
      int touchPin_1_val = digitalRead(touchPin_1);
      int touchPin_2_val = digitalRead(touchPin_2);
    
      if (touchPin_1_val == HIGH || touchPin_2_val == HIGH) { //if either of the sensors are triggered...
          isLightOn = !isLightOn; //toggle light state
      }
    
      if (isLightOn) { //if the light state is true, or set to 'on'...
          Serial.println("light on");
          digitalWrite(relayPin, HIGH); //on
      } else {
          Serial.println("light off");
          digitalWrite(relayPin, LOW); //off
      }
    
      delay(100);
      }`