[Solved] Simple Button Program Problem

Hello everyone,
I've just got the Arduino UNO yesterday, and I had a problem with a simple program.
the program is when the push button is pressed LED1 is ON and LED2 is OFF and when released LED1 is OFF and LED2 is ON.
what happens is LED2 is always OFF :|, and LED1 is switching normally as it should.
if anyone could help, I'll appreciated.

here's the code:

int PushButton = 2;
int LED1 = 3;
int LED2 = 4;

void setup() {
 pinMode(PushButton,INPUT);
 pinMode(LED1,OUTPUT);
 pinMode(LED2,OUTPUT);
}
 
void loop() {
  if (digitalRead(PushButton)==HIGH) {
    digitalWrite(LED1,HIGH);
    digitalWrite(LED2,LOW);
  }
  if (digitalRead(PushButton)==LOW) {
   digitalWrite(LED1,LOW);
   digitalWrite(LED2,HIGH);
  } 

}

And about my connections, I've connected the switch with a pull down resistor 220ohm, and the two LEDs are connected to the digital pins 3 and 4 through 220ohm resistors.
I've checked for the LEDs and the wires and everything is just fine.

First thing i would check is the polarity of the second LED, then whether it works at all by switching with the other led.
TomJ

swap the LED's around.

  1. add a debounce (or a capacitor to keep the voltage raised or in that brief moment you've pressed the button it can measure the metal contacts touching each other hundreds of times, the cap stops that) routine eg... AnalougeRead.... {Delay(250); (enough to get your finger off in time) your code}

Mashadawy:
And about my connections, I've connected the switch with a pull down resistor 220ohm

Show how you connected this. The resistor is too small as pull down, try 10K or 20K not 220. Why not trying to use the internal pull_up resistor. Just add digitalWrite(button,HIGH); after pinMode() to enable the internal pull_up resistor. Then connect the pin to button, the button other side to gnd.

it worked, I made a software debouncing for the switch, and enabled the internal pull-up resistors, and it worked just perfect.
thx everybody for the help, really appreciated. :slight_smile: