This sketch will:
- Define all the relays, and the ESP32's internal LED
- Turn on Relay1, blink internal LED once
- Wait four seconds
- Turn off Relay1, turn on Relay2, blink internal LED twice
- Wait four seconds, turn off Relay2 and start over
- It also writes to the serial monitor when a relay is turned on or off, and uses two different ways of blinking the LED
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
Become a Hackaday.io Member
Create an account to leave a comment. Already have an account? Log In.