Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * Example of how to turn on two relays with a delay and blink an LED while turning on.
- *
- * Inspired by a reddit post:
- * https://www.reddit.com/r/arduino/comments/r4phym/how_to_turn_on_two_relays_one_instantly_one/
- *
- * By gm310509
- * November-2021
- *
- */
- const int LED = 3; // an actual LED
- const int RELAY0 = 5; // first relay 1
- const int RELAY1 = 6; // aka relay 2
- const int BUTTON = 2;
- const int ON_DELAY_MS = 5000; // Delay between turning relay 1 and 2 in ms (i.e. 5000 = 5 seconds).
- const int BLINK_INTERVAL = 250;
- void setup() {
- Serial.begin(115200);
- while (!Serial) {
- }
- pinMode(LED, OUTPUT);
- pinMode(RELAY0, OUTPUT);
- pinMode(RELAY1, OUTPUT);
- pinMode(BUTTON, INPUT);
- }
- void loop() {
- static boolean relaysOn = false; // relay status on or off - initially off.
- static boolean turningOn = false; // true if we are in the process of turning the relays on.
- static unsigned long nextStepTime = 0; // when to take the next step.
- static unsigned long nextBlinkTime = 0; // when to blink the LED.
- static int prevBtnState = HIGH;
- unsigned long now = millis(); // Get current "time" ready for the rest of this block of code..
- int btnState = digitalRead(BUTTON); // Read the button state
- if (btnState != prevBtnState) { // Has it changed state? (i.e. pressed or released)
- prevBtnState = btnState;
- delay(10); // This a simplistic way to debounce the button.
- if (btnState == LOW) { // Button has been pressed.
- if (relaysOn) { // Are they on?
- digitalWrite (RELAY0, LOW); // Yes, turn everything off.
- digitalWrite (RELAY1, LOW);
- digitalWrite (LED, LOW);
- relaysOn = false; // indicate that everything is off.
- delay
- } else if (!turningOn) { // Are we in the middle of turning the relays ON
- // No we are not in the middle of turning them on,
- // so initiate the turning on process.
- turningOn = true;
- digitalWrite (RELAY0, HIGH); // turn the first two things on.
- digitalWrite (LED, HIGH);
- nextStepTime = now + ON_DELAY_MS; // Work out when to turn the next one on.
- nextBlinkTime = now + BLINK_INTERVAL; // Same for the blinking of the LED.
- } else { // We are in the middle of turning the relays on, so what to do?
- // I do not know, so right now, do nothing.
- }
- }
- }
- if (turningOn) { // Are we turning stuff on?
- // Yes, so check if it is time to perform the next step
- if (now >= nextBlinkTime) { // Blink the LED?
- nextBlinkTime = now + BLINK_INTERVAL; // Calculate the next time to change the LED
- digitalWrite(LED, ! digitalRead(LED)); // invert the LED.
- }
- if (turningOn && now >= nextStepTime) {
- digitalWrite(RELAY1, HIGH); // turn on the second relay
- relaysOn = true; // The relays are no all on
- turningOn = false; // And we are done with the turning on process.
- }
- }
- }
Add Comment
Please, Sign In to add comment