Close

Simple sketch - Switch between Relay1 and 2, every 4 seconds

A project log for Muffsy Stereo Relay Input Selector

Open Source, versatile audio relay input selector controlled by an ESP32

skrodahlskrodahl 03/31/2018 at 15:530 Comments

This sketch will:

This shows how to turn on and off relays. Remember, you can connect an LED between the relay1-5 IO pins together with a 330 ohms resistor to GND. This LED will light up when the corresponding relay is active.

The ESP32 has the capability to store the last selected relay, so it can be selected directly if the device is turned off and on again. (not shown here)

Instead of just looping through the relays you can use push buttons, a potentiometer or a rotary encoder (and lots of other things that can hook up to the ESP32) to decide which relay is turned on.

#define LED   2       // Internal LED
#define relay1 23     // relay1 on IO23
#define relay2 22     // relay2 on IO22
#define relay3 21     // relay3 on IO21
#define relay4 19     // relay4 on IO19
#define relay5 18     // relay5 on IO18

void setup()
{
    pinMode(relay1, OUTPUT);
    pinMode(relay2, OUTPUT);
    pinMode(relay3, OUTPUT);
    pinMode(relay4, OUTPUT);
    pinMode(relay5, OUTPUT);
    pinMode(LED, OUTPUT);
    Serial.begin(115200);
}

void loop()
{
    // Turn on relay1
    Serial.println("Relay #1 - ON");
    digitalWrite(relay1, HIGH);
    
    // Blink internal LED once
    digitalWrite(LED, HIGH);
    delay(200);
    digitalWrite(LED, LOW);

    // Wait 4 seconds
    delay(4000);

    // Turn off relay1
    // Turn on relay2
    Serial.println("Relay #1 - OFF");
    digitalWrite(relay1, LOW);
    Serial.println("Relay #2 - ON");
    digitalWrite(relay2, HIGH);

    // Blink internal LED twice
    for (int counter=0; counter<2; counter = counter+1){
      digitalWrite(LED, HIGH);
      delay(200);
      digitalWrite(LED, LOW);
      delay(200);
    }

    // Wait 4 seconds
    delay(4000);

    // Turn off Relay2
    Serial.println("Relay #2 - OFF");
    digitalWrite(relay2, LOW);
}

Discussions