Button for On Off and timer

Hello I've learn a lot from this comunity. This is mty first post :smiley:

I have a problem with a project I'm trying to add a timer for an output ex. LED. The thought is If push button1 then set Led High for 20min or If I push it again set Led LOW.

I' ve got this code and I do not want to use delay, becaouse I have an LCD that takes data from a temp sensor.

int pinButton = 2;
int LED = 6;
int stateLED = LOW;
int stateButton;
int previous = LOW;
long time = 0;
long debounce = 700;

void setup() {
pinMode(pinButton, INPUT);
pinMode(LED, OUTPUT);
}

void loop() {
stateButton = digitalRead(pinButton);
if(stateButton == HIGH && previous == LOW && millis() - time > debounce) { //if button is pressed and LED is off
if(stateLED == HIGH){
stateLED = LOW;
} else {
stateLED = HIGH;
}
time = millis();
}
digitalWrite(LED, stateLED);
previous == stateButton;
}

  previous == stateButton;

Why do you care if previous equals stateButton, when you don't do anything either way?

There does NOT appear to be any relationship between previous and stateButtton, so it is not obvious why you are comparing them. currentState and previousState DO appear to be related.

Split it into separate parts. A turn on (led is off and button becomes pressed) and a turn off (led is on and (time elapsed or button becomes pressed)).

And if you want easy, grab a library to handle the button debounce and state change detection like Bounce2.

Could you give an exapmle plz. I'm trying to lear be reading code and examples.

nbillis:
Could you give an exapmle plz. I'm trying to lear be reading code and examples.

In fact, there are button debounce and LED timing examples supplied with the IDE. You can access them from the File->Examples menu.

I'm trying to lear

Well, stop that. Learing is rude.

:slight_smile:

#include <Bounce2.h>

//Pins
const byte ButtonPin = 2;
const byte LedPin = 6;

//Other settings
const unsigned long MaxOnTime = 20 * 60 * 1000UL;

unsigned long turnOnMillis;
Bounce button;

void setup(){
	button.attach(ButtonPin, INPUT_PULLUP);
	pinMode(LedPin, OUTPUT);
	
}

void loop(){
	button.update();
	if(!digitalRead(LedPin) && button.fell()){
		digitalWrite(LedPin, HIGH);
		turnOnMillis = millis();
	}
	else if(digitalRead(LedPin) && (button.fell() || (millis() - turnOnMillis >= MaxOnTime))){
		digitalWrite(LedPin, LOW);
	}
}

Excelent !!

with a little corection "button.attache(ButtonPin, INPUT_PULLUP);"

"button.attach(ButtonPin, INPUT_PULLUP);"

Thank you.

That's what it says, isn't it? :smiling_imp: