MrAlvin

Arduino - Turn on/off lamp for 5 seconds, when button is pushed, with timer reset button option

Jul 26th, 2020 (edited)
403
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.79 KB | None | 0 0
  1. // Turn ON/OFF a Relay/LED, when button is pushed
  2. // Relay Automatically turns OFF/ON again after 5 seconds (it is possible to adjust interval)
  3. // With option to reset the timer - so Relay turns ON/OFF at push of 'reset timer button'
  4.  
  5. const int SetPin = 6;     //pin connected to ON button - (other side of button is connected to ground/minus)
  6. const int ResetPin = 7;   //pin connected to 'Reset timer button' - (other side of button is connected to ground/minus)
  7. const int relayPin = 9;   //pin connected to control of Relay/LED
  8.  
  9. //makes it easy to switch between relays that are controlled by HIGH or LOW signal
  10. const int RELAY_ON = HIGH;  
  11. const int RELAY_OFF = LOW;
  12.  
  13. int buttonState1 = 0;
  14. int buttonState2 = 0;
  15.  
  16. unsigned long timerMillis = 0; // is set when timer is started
  17. unsigned long interval = 5000; // interval of the timer - (time that the LED/relay is ON)
  18.                                // (1000 = 1 second), (60000 = 1 minute), (600000 = 10 minutes)
  19.  
  20. int ledStatus = 0;   // is used to keep track of relay/LED status
  21.  
  22. void setup() {
  23.   pinMode(relayPin, OUTPUT);
  24.   pinMode(SetPin, INPUT_PULLUP);
  25.   pinMode(ResetPin, INPUT_PULLUP);
  26.   digitalWrite(relayPin, RELAY_OFF);
  27. } // End - setup()
  28.  
  29. void loop() {
  30.   // read buttons  
  31.   buttonState1 = digitalRead(SetPin);
  32.   buttonState2 = digitalRead(ResetPin);
  33.  
  34.   // take action if a button was pressed
  35.   if (buttonState1 == LOW) {
  36.     digitalWrite(relayPin, RELAY_ON);
  37.     ledStatus = 1;
  38.   }
  39.   if (buttonState2 == LOW) {
  40.     digitalWrite(relayPin, RELAY_OFF);
  41.     ledStatus = 0;
  42.   }
  43.  
  44.   // if relay is ON, then check to see if timer has expired
  45.   if (ledStatus == 1) {
  46.     if (millis() - timerMillis >= interval) {
  47.       timerMillis = millis();
  48.       digitalWrite(relayPin, RELAY_OFF);
  49.       ledStatus = 0;
  50.     }
  51.   }
  52. } // End - loop()
Add Comment
Please, Sign In to add comment