On-Delay Timer Program

Hi,

I am trying to write a program that will create an on-delay timer for an output. Pressing a button is supposed to enable the timer. What I have so far causes the button to enable the output when the timer finishes counting up to 5 seconds from when the program starts running.

My question is how do I write the program where the timer is activated by the button, not when the program begins?

Below is what I have so far:

unsigned long startMillis;
unsigned long currentMillis;
const unsigned long period = 5000; //the value is a number of seconds (1 period is 5 seconds)
const byte ledPin = LED_BUILTIN; //using the built-in LED
const int switchPin = 2;
boolean state;

void setup() {
// put your setup code here, to run once:
pinMode(ledPin, OUTPUT);
pinMode(switchPin, INPUT); //input for pushbutton switch
}

void loop() {
// put your main code here, to run repeatedly:
state = digitalRead(switchPin); //read the state of the pushbutton switch
currentMillis = millis(); //get the current “time” (actually the number of milliseconds since the program started)

if (state == true) //test whether the period has elapsed
{
if (currentMillis - startMillis >= period)
{
digitalWrite(ledPin, HIGH);
}
else {digitalWrite(ledPin, LOW);}
}
}

What about setting currentMillis = millis() AFTER you've decided that the button has been pressed?

Steve

I'll try that and report back.

Thanks!

Where does startMillis ever get a new value?

What is that variable supposed to hold the start of?

Using meaningful names isn't hard. It's usually easier than using meaningless names.

It's supposed to hold the start of the timer after the button was pressed.

PaulS:
Where does startMillis ever get a new value?

What is that variable supposed to hold the start of?

Using meaningful names isn't hard. It's usually easier than using meaningless names.

My apologies, I understand what you're saying better.

Part of my issue here is I don't understand what I should assign this variable to, in order to make the timer start when the button is pressed.

Thanks

jhend1000:
It's supposed to hold the start of the timer after the button was pressed.

Wouldn't switchPressedTime then make more sense? Would that name suggest when you should assign it a value?

Testing when the period has elapsed, as your comment states, when the switch IS pressed doesn't make sense.

You REALLY need to look at the state change detection example. You REALLY need to explain how your switch is wired.

The button is connected to pin 2. I am using it as an active high input with a 10k Ohm pull-down resistor attached to +5V.

At this point, since I'm still fairly new to this, I am just going to do more research first and try to educate myself better.

Thanks for the assistance, nonetheless.