Button Relay Control How can I fix this sketch to make it so that once the button is pressed, it performs some action for a certain amount of time and then returns back to a low state until it is pressed again. For example, I need to run a pump for 5 seconds when the button is pressed and then turn off automatically. And then, when I press the button again it will repeat, etc. I am not trying to use a relay module if it is not necessary. Here is my current sketch and a Lab View of the components: 



#include &lt;LiquidCrystal.h&gt;
#include &lt;SoftwareSerial.h&gt;


int switchPin = 8;
int ledPin = 13;
int buttonPresses = 0;
boolean lastButton = LOW;
boolean currentButton = LOW;
boolean ledOn = false;

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup()
{
  Serial.begin(9600);
  pinMode(switchPin, INPUT);
  pinMode(ledPin, OUTPUT);
  lcd.begin(16, 2);
}

boolean debounce(boolean last) //just a debounce function
{
  boolean current = digitalRead(switchPin);
  if (last != current)
  {
    delay(5);
    current = digitalRead(switchPin);
  }
  return current;
}

void loop()
{
  {currentButton = debounce(lastButton);
  if (lastButton == LOW &amp;&amp; currentButton == HIGH)
  {
    ledOn = !ledOn;

    buttonPresses++;
    lcd.clear();
    lcd.print("Number of Button ");
    lcd.setCursor(0,1);
    lcd.print("Presses = ");
    lcd.print(buttonPresses);  
  }
   lastButton = currentButton;
   digitalWrite(ledPin, ledOn);
  }
}


THANK YOU!
This code should work. You will need to declare the following variables:


lastPress   // The last time the button was pressed
outputState  // The state of the timed output 
outputPin  // The pin number for the timed output
PERIOD  // The amount of time that the outptu remains on


The code:

void loop()
{
    currentButton = debounce(lastButton);
    if (lastButton == LOW &amp;&amp; currentButton == HIGH)
    {
        ledOn = !ledOn;

        buttonPresses++;
        lcd.clear();
        lcd.print("Number of Button ");
        lcd.setCursor(0,1);
        lcd.print("Presses = ");
        lcd.print(buttonPresses);

        outputState = HIGH;
        lastPress = millis();  
    }

    if (outputState &amp;&amp; ((millis() - lastPress) &gt; PERIOD))
    {
        outputState = LOW;
    }

    digitalWrite(outputPin, outputState);

    lastButton = currentButton;
    digitalWrite(ledPin, ledOn);
}


A relay should be used to drive a pump etc.. The Arduino Uno can only drive 5V at maximum 20mA.