2 buttons works simultaneously

Hi! good day to all,
I have a simple question regarding my 2 buttons I want my buttons to work simultaneously. the problems are when I pressed the first button the other button is not working, I need to wait for the first button to finish before the other button works.

int button1 = A0;
int button2 = A1; 
int ledPin1 = 7;
int ledPin2 = 8;
int buzzer = 2;  

void setup() {
  pinMode(ledPin1, OUTPUT);
  pinMode(ledPin2, OUTPUT);
  pinMode(buzzer, OUTPUT);
  pinMode(button1, INPUT);
  pinMode(button2, INPUT);
}

void loop() {
 if (digitalRead(button1) == HIGH) {
    digitalWrite(ledPin1, HIGH);
    digitalWrite(buzzer, HIGH);
    delay(3000);
    digitalWrite(buzzer, LOW);    
  }
  else {
    digitalWrite(ledPin1, LOW);
    digitalWrite(buzzer, LOW);  
  }
 if (digitalRead(button2) == HIGH) {
    digitalWrite(ledPin2, HIGH);
    digitalWrite(buzzer, HIGH);
    delay(3000);
    digitalWrite(buzzer, LOW);   
  }
  else {
    digitalWrite(ledPin2, LOW);
    digitalWrite(buzzer, LOW);  
  }
}

get rid of the delay()s, and read up on millis() timing.

The delay() function causes the code to block. During a delay() the processor is doing noting. Look at the blink wthout delay example in the IDE examples and do a search for the several things at a time tutorial to learn how to write code withiut delay() (non-blocking code).

Also the beginners guide to millis().

ok thank you guys for quick reply.

Also read up on state machine programming.

follow up question its weird when I pressed the first button the LED works but the buzzer's not but when I pressed both buttons the buzzers work along with the LED's!.

How are the switches wired? Do you have a pullup or pulldown resistor installed?

The common way to wire switches is one side to ground and the other side to an input with its pinMode set to INPUT_PULLUP. The switch will read HIGH when not pressed and LOW when pressed.

Hello lgathana

Welcome to the worldbest Arduino forum ever.

Take a view to gain the knowledge.

Have a nice day and enjoy coding in C++.

yes I have pull up resistors for both buttons. I just remove the above codes

Question:
Should the buzzer be switched on or off together with the LEDs?

If the only thing that you have done is removing these two lines of code and did nothing else
it is vey normal that your code now works different than with having these two lines of code.

You will have to change the code to work non-blocking.

Writing code that is non-blocking works different than blocking code that uses delay()
Again: with delay() you can do nothing else than wait until the delay() has finished.

And this is the reason way it must be coded non-blocking.

best regards Stefan

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.