You haven't told us about your circuit.
Also what else do you have in the code?
If you have a normally-open pushbutton, you can wire one end to GND, and the other to a pin, say pin 2;
In the code you set pin 2's mode to be INPUT_PULLUP. This enables a resistor internally so that the pin doesn't float high or low, its default state is pulled HIGH via the resistor.
Next, you have [at least] 2 choices here. you can frequently poll the value of the push button to determine if it's pressed, or you can set up an interrupt [preferred, but has to be on interrupt-enabled pin - see here]
Here is an example of that [not tested on board, but will compile]:
int pin = 2;
int led = 5;
void setup()
{
pinMode(pin, INPUT_PULLUP);
pinMode(led, OUTPUT);
attachInterrupt(0, isr, FALLING);
}
volatile long last = 0;
volatile bool turnOff = false;
volatile long offAt = 0;
void isr()
{
if( (millis() - last ) > 20 ) //if at least 20 ms has passed since last press, this is not a dup
{
last = millis(); //note the time, for ignoring duplicate presses
turnOff = true;
offAt = millis() + 5000; //save a variable of now + 5 seconds
digitalWrite(led, HIGH); //turn on
}
}
void loop()
{
if(turnOff)
{
if(millis() >= offAt)
{
digitalWrite(led, LOW); //turn off led
}
}
}
if you just wanted to poll the button in loop() instead, you can, and if you have nothing else going on that would be ok.
example:
int pin = 2;
int led = 5;
void setup()
{
pinMode(pin, INPUT_PULLUP);
pinMode(led, OUTPUT);
}
long offAt = 0;
void loop()
{
if( (digitalRead(led) == LOW ) && (digitalRead(pin) == LOW) ) //if LED is off and button is pressed [low because it has pullup resistor]
{
digitalWrite(led, HIGH);
offAt = millis() + 5000; //store var of now + 5 seconds
}
if(digitalRead(led) == HIGH) //if led is on
{
if(millis() >= offAt) //see if it's time to turn off LED
{
digitalWrite(led, LOW); //it's time. this also re-enables the button
}
}
}
For that one, if you press the button, and LED is on, any more button presses will be ignored until the led is off again.