Should I use a loop instead of an If statement? I have a simple sketch that tests input from 2 touch sensors and outputs to 2 relays (if a sensor is touched, trigger the respective momentary relay).  It has been a bit quirky to say the least.  perhaps I need to adjust delays or adjust sensitivity of the touch sensors, but I feel that maybe the coding could be more efficient.  Would using a WHILE or DOWHILE loop work better than an IF statement for this?  It seems like there is a timing issue between the relay and the sensor.  When I hit the sensor, the relay triggers immediately, but then it doesn't shut off right away.  Also if both sensors are made at the same time, I am seeing only 1 relay trigger or neither.  I am trying to eliminate the code as my failure point. I have the code printing to the serial monitor to show "Sensor 1 touched" or "Sensor 2 touched", and sometimes that triggers once and sometimes it will print multiple times.

int touchPin1 = 2; //Touch sensor 1
int touchPin2 = 4; //Touch sensor 2
int val_1 = 0; 
int val_2 = 0; 
int relayPin1 = 8; //Relay 1
int relayPin2 = 9; //Relay 2

void setup() 
{
  Serial.begin(9600);
  pinMode(touchPin1, INPUT); 
  pinMode(touchPin2, INPUT);
  pinMode(relayPin1, OUTPUT);
  pinMode(relayPin2, OUTPUT);

}

void loop() {
  digitalWrite(relayPin1, LOW);
  digitalWrite(relayPin2, LOW);
  val_1 = digitalRead(touchPin1);
  val_2 = digitalRead(touchPin2);  
  if(val_1 ==1)
  {
  Serial.println("Pad 1 Touched");
  digitalWrite(relayPin1, HIGH);
  }
  if(val_2 ==1)
  {
  Serial.println("Pad 2 Touched");
  digitalWrite(relayPin2, HIGH);
  }
  delay(100);
  //Serial.println();
}


Basically I am asking if there is a more efficient way to code this.

Touch Sensors: Adafruit Standalone Momentary Capacitive Touch Sensor Breakout Adafruit Part Number: 1374 

Relays: SunFounder Relay Module for Arduino and Raspberry Pi 5V DC Trigger by HIGHLO (HIGH Trigger)
What you are lacking is the else concept:


If a touch pad is pressed, then


Turn the relay on

else


Turn the relay off



Rather than turn the relay off every iteration, you only turn it off if the touch pad is not pressed.

That can be written as:

val_1 = digitalRead(touchPin1);

if(val_1 ==1)
{
  Serial.println("Pad 1 Touched");
  digitalWrite(relayPin1, HIGH);
} else {
  digitalWrite(relayPin1, LOW);
}


If you want your messages to be more meaningful and not spam, then you can remember the previous state and only do things if the state changes:

static uint8_t oldVal1 = LOW;

uint8_t val1 = digitaRead(touchPin1);

if (val1 != oldVal1) {
    oldVal1 = val1;
    if (val1 == HIGH) {
        Serial.println("Pad 1 Touched");
        digitalWrite(relayPin1, HIGH);
    } else {
        Serial.println("Pad 1 Released");
        digitalWrite(relayPin1, LOW);
    }
}