0

I have 2 LEDs and 2 buttons. What I want to code is when first button pressed the 1st LED turn on (stay on for 5 seconds) and 2nd LED remain off, and same if 2nd button pressed the 2nd LED turn on and 1st LED remain off. I want the processing reset after 5 seconds. Here is my work, what it does now is 1st LED turn on when I press 1st button, but the 2nd button and 2nd LED still can press and light up right after. I want the 2nd button deactivate when 1st button pressed for 5 seconds. Please give me basic program because I am new to this.

int pinButton_1 = 8; //the pin where we connect the button
int pinButton_2 = 9;
int LED_1 = 1; //the pin we connect the LED
int LED_2 = 2;
void setup() {
  pinMode(pinButton_1, INPUT); //set the button pin as INPUT
  pinMode(pinButton_2, INPUT);
  pinMode(LED_1, OUTPUT); //set the LED pin as OUTPUT
  pinMode(LED_2, OUTPUT);
}

void loop() {
  int stateButton_1 = digitalRead(pinButton_1); //read the state of the button
  int stateButton_2 = digitalRead(pinButton_2); //read the state of the button
  if(stateButton_1 == 1) { //if is pressed
     digitalWrite(LED_1, HIGH); //LED_1 on
     digitalWrite(LED_2, LOW); //LED_2 off
     delay(50);
  }
     if (stateButton_2 == 1) {
      digitalWrite(LED_1, LOW);
      digitalWrite(LED_2, HIGH);
      delay(50);
     }
  }

1 Answer 1

1

First of all you have not implemented a stay on time of 5seconds delay(5000); but only 50ms delay(50);.

Second, you are not really switching of your LED's if no further button is pressed.

Change your loop() to the following, I guess this will help you to start your next steps into getting familiar with your code:

    void loop() {
      int stateButton_1 = digitalRead(pinButton_1); //read the state of the Button_1
      if(stateButton_1 == 1) {      //if Button_1 is pressed
         digitalWrite(LED_1, HIGH); //LED_1 on
         digitalWrite(LED_2, LOW);  //LED_2 off
         delay(5000);
      }
      digitalWrite(LED_1, LOW); //Switch off LED_1

      int stateButton_2 = digitalRead(pinButton_2); //read the state of the button 2
      if (stateButton_2 == 1) {
         digitalWrite(LED_1, LOW);
         digitalWrite(LED_2, HIGH);
         delay(5000);
      }
      digitalWrite(LED_2, LOW); //Switch off LED_2
    }

Hint: Using delay() is often not a good construct, better to do it with millis(), but this means some more changes. For the start in your case delay() will do, but check out what here in different Questions/answers is already written about delay() vs. millis()

1
  • thank you for your help, I really appreciated
    – tripleT
    Mar 27, 2019 at 21:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.