MrAlvin

Arduino - Turn off a lamp for 5 seconds, when button is pushed

Jul 25th, 2020 (edited)
1,820
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.48 KB | None | 0 0
  1. // Turn OFF a LED, for some time (interval), when a button is pushed
  2.  
  3. // - wire Arduino pin to button
  4. // - wire other side of button to ground/minus
  5. //   so a push of the button will pull Arduino pin LOW
  6.  
  7. const int pushButton = 7;
  8. const int LedPin = 6;
  9.  
  10. int buttonState = HIGH;   //power-on state - when button is NOT pushed
  11. int ledState = HIGH;      //power-on state - LED is ON
  12.  
  13. //timing variables
  14. unsigned long holdMillis = 0;        // save the time when the button was pushed
  15. unsigned long interval = 5000;       // save the LED OFF interval - default is 5 seconds
  16.                                      // 10 minutes is: (10 min x 60 seconds x 1000 milli seconds = 600000)
  17.  
  18.  
  19. void setup() {
  20.   pinMode(pushButton, INPUT_PULLUP);
  21.   pinMode(LedPin, OUTPUT);
  22.  
  23.   //turn ON LED
  24.   digitalWrite(LedPin, ledState);
  25. } //end - setup()
  26.  
  27.  
  28. void loop() {
  29.  
  30.   //if LED is ON, check button
  31.   if (ledState == HIGH) {
  32.     //read button state
  33.     buttonState = digitalRead(pushButton);
  34.    
  35.     //if button is pushed (is LOW) then take action
  36.     if (buttonState  == LOW) {
  37.       //turn OFF LED
  38.       ledState = LOW;
  39.       //remember the current time
  40.       holdMillis = millis();
  41.     }
  42.   }else{
  43.   // LED is OFF - so check to see if time has passed
  44.  
  45.     //has the time passed
  46.     if ( millis() - holdMillis >= interval ) {
  47.       //then turn ON LED
  48.       ledState = HIGH;
  49.     }
  50.   } // end - if(ledSTATE)
  51.  
  52.   //update LED pin
  53.   digitalWrite(LedPin, ledState);  
  54. } //end - loop()
Add Comment
Please, Sign In to add comment