Help on 2 problems with pushbutton controlling LED

Hi guys,
I am a beginner and have 2 problems with the code below. I hope that you help me solving them:
1- When button1 or 2 is pressed and released, LED1 or 2 shouldn't remain HIGH. I need the LED to turn LOW after a delay of certain time, e.g. 30sce. It also should return LOW if the button is pushed again before the delay time is up.
2- When button1 is pressed and released, LED1 goes HIGH after the delay time(3000). The problem is that button2 does not work to turn LED2 HIGH or LOW until after that delay time is up. I need to control each LED separately.
Any help would be much appreciated!
Many thanks, :slight_smile:

#define LED1 8
#define LED2 13
#define BUTTON1 7
#define BUTTON2 6

int val1 = 0;
int val2 = 0;
int old_val1 = 0;
int old_val2 = 0;
int state1 = 0;
int state2 = 0;

void setup() {
  pinMode(LED1, OUTPUT);
  pinMode(BUTTON1, INPUT);
  pinMode(LED2, OUTPUT);
  pinMode(BUTTON2, INPUT);
}
void loop(){
  val1 = digitalRead(BUTTON1);
  val2 = digitalRead(BUTTON2);
   if ((val1 == HIGH) && (old_val1 == LOW)){
    state1 = 1 - state1;
    delay(3000);
   }
     if ((val2 == HIGH) && (old_val2 == LOW)){
    state2 = 1 - state2;
    delay(300);
  }
  old_val1 = val1;
  if(state1 == 1) {
    digitalWrite(LED1, HIGH); 
} else {
    digitalWrite(LED1, LOW);
  }
  
  old_val2 = val2;
  if(state2 == 1) {
    digitalWrite(LED2, HIGH);
  } else {
    digitalWrite(LED2, LOW);
  }
   }

Delay effectively kills the processor, so if you want to cut short something thats waiting, you can't use delay, because the processor won't do anything until the delay ends. Take a look at the blink without delay in the digital section of the examples in the IDE.

Thank you pluggy for the quick reply!
does that apply to the two problems I have?
I took a look at the example you mentioned but, as I am a beginner, it didn't help me. However, it says that two codes can be run at a time, which I need in my project.
Does that mean I only need to change the sketch to control each LED separately? If so, could you please tell me how?

thank you,

I'm not going to write the code for you, but heres what I would do.

In your main loop assign a variable to the value of millis(); Keep a boolean variable for each switch in the loop so its monitoring the state all the time. Then write some if thens that look at the state of the swirtch and assign variables to the time that something is expected to happen - if you want it to turn an LED on and then off in three seconds it would be something like :

time = millis();
if (button1 = 1){digitalWrite(LEDPin,HIGH); timeLEDoff = millis() + 3000;};

then later in the loop have something like :

if (time >= timeLEDoff){digitalWrite(LEDPin,LOW);};

You get the idea.......

You shouldn't have any delays in the sketch at all.