I`m struggling with a school task and was hoping you guys could help me.
I have two buttons, and when I press one of them, doesnt matter which, a LED is going to light up. Thats the easy part.
The rest of the task is to get the LED to blink when you hold both buttons down at the same time. I have tried to do this in my code, but now the LED blinks when I only hold 1 button. :~ Any help is appreciated.
const int led = 5;
const int button = 7;
const int button2 = 8;
int buttonstate = 0;
int buttonstate2 = 0;
void setup(){
 pinMode(led, OUTPUT);
 pinMode(button, INPUT);
 pinMode(button2, INPUT);
}
void loop(){
buttonstate = digitalRead(button);
buttonstate2 = digitalRead(button2);
  if (buttonstate == HIGH || buttonstate2 == HIGH)
 {
 digitalWrite (led, HIGH);
}
 else{
  digitalWrite (led, LOW);
 }
Â
Â
Â
 if (buttonstate == HIGH && buttonstate2 == HIGH)
{
 digitalWrite(led, HIGH);
 delay(500);
 digitalWrite(led, LOW);
 delay(500);
}
else{
 digitalWrite(led, LOW);
}
}
Make sure your buttons have pull down resistors or switch the code to use the internal pull resistors and look for when the button are brought LOW instead of HIGH.
You can also fool proof this line if (buttonstate == HIGH || buttonstate2 == HIGH) by checking to see if the buttons are just pressed individually.
if ( (buttonstate == HIGH || buttonstate2 == HIGH) && !(buttonstate == HIGH && buttonstate2 == HIGH) )
You can also combine the two different IF statements into IF, ELSE IF, ELSE, because they both return to LOW when not pressed.
HazardsMind:
Make sure your buttons have pull down resistors or switch the code to use the internal pull resistors and look for when the button are brought LOW instead of HIGH.
Yeah I have 10K ohm resistors connected to the buttons.