Alternate between 2 relays with one button I have a very basic programming knowledge, but the thing I want to achieve is to alternate between switching 2 relays with a button or a RPi input pulse.

So something like this:


Press the button
Switch relay 1 on and off (1 second delay)
Press the button
Switch relay 2 on and off
Press the button
Switch relay 1 on and off (1 second delay)
Press the button
Switch relay 2 on and off
Press the button
Switch relay 1 on and off (1 second delay)
Press the button
Switch relay 2 on and off
etc.


Here's my code, I thought if I'd just put the second relay after the first else everything would work. But I'm missing some basic knowledge to figure this out.

const int ledPin = 2;
const int ledPinA = 3;

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

void loop() {
  int sensorValue = analogRead(A0);
  Serial.println(sensorValue);
  delay(1);
  if (sensorValue &gt; 500) {
    digitalWrite(ledPin, HIGH);
  } else {
    digitalWrite(ledPin, LOW);
  }
  if (sensorValue &gt; 500) {
    digitalWrite(ledPinA, HIGH);
  } else {
    digitalWrite(ledPinA, LOW);
  }
}


I'm thinking I should use while.
The way you have it, both if blocks will be evaluated each time you call to loop(). Instead, you need to create a variable that remains "alive" in between each call to loop() to keep track of which relay you want to activate:

const int ledPin = 2;
const int ledPinA = 3;
int active_relay = 2;   // State variable for current relay pin

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

void loop() {
      int sensorValue = analogRead(A0);

      Serial.println(sensorValue);

      delay(1);    // This delays for 1ms, not 1s ??

      if (sensorValue &gt; 500) {   // Pulse received
          digitalWrite(active_relay, HIGH);  // Relay on
          delay(1000);                       // Wait 1 second
          digitalWrite(active_relay, LOW);   // Relay off

          // Update variable for next call to loop
          if (active_relay == ledPin) {
              active_relay = ledPinA;      // Swap
          }
          else {
              active_relay = ledPin;       // Swap
          }
      }
      // Remove 2nd if block
}