Having a problem with my code consistently doing the correct thing

I am trying to create a toggle switch that turns On or Off an LED depending on its current state. If I press the button and it's On, I want it to turn Off the LED and visa-versa.

What happens with my current code is that it will work.... sometimes. The LED is off, then I press and release the button, the LED turns ON, then I press and release the button, the LED goes off. But sometimes it just stays On when I press the button or it doesn't turn On at all.

I wired 5v into 1 side of a momentary switch. On the other end I wired a 1K resistor to the negative side of the switch to pull down for any noise in the circuit and connected also the negative to Digital Input 2 on the Arduino. The positive side of the LED is wired to Digital Output 13 on the Arduino and the negative side is wired to the negative terminal with a 220K resistor.

As you can see from the code below I am using an "if" statement to test if the button is pressed and if the LED is On or not. Then I perform the appropriate digitalWrite to either turn the LED On or Off depending on the LED's current state.

int ledPin = 13;
int switchPin = 2;

void setup() {
  pinMode(ledPin, OUTPUT);
  pinMode(switchPin, INPUT);
}

void loop() {
  if (digitalRead(switchPin) == LOW && digitalRead(ledPin) == HIGH) {
    digitalWrite(ledPin, HIGH);
  }
  else if (digitalRead(switchPin) == LOW && digitalRead(ledPin) == LOW) {
    digitalWrite(ledPin, LOW);
  }
  else if (digitalRead(switchPin) == HIGH && digitalRead(ledPin) == HIGH) {
    digitalWrite(ledPin, LOW);
  }
  else if (digitalRead(switchPin) == HIGH && digitalRead(ledPin) == LOW) {
    digitalWrite(ledPin, HIGH);
  }
delay (5);
}

Can I perform a digitalRead on a pin I specified as an OUTPUT?
Is there a better way to accomplish this?

Any help is greatly appreciated!

Your switch is bouncing.
Search for debounce examples.
Yes you can read a output pin with digital read.

Your switch is bouncing.

May be, not is.

You really should look at the state change detection example. You want to change the state of the LED when the switch BECOMES pressed, not IS pressed.

Does this have the same symptoms

int ledPin = 13;
int switchPin = 2;

void setup() {
  pinMode(ledPin, OUTPUT);
  pinMode(switchPin, INPUT);
}

void loop() 
{
  while (digitalRead(switchPin) == HIGH) {} ; // just wait until key is released
  delay(5);
  while (digitalRead(switchPin) == LOW ) {} ; // just wait until key is pressed
  delay(5);
  digitalWrite(ledPin, !digitalRead(ledPin));
}

Thanks for pointing me in the right direction. I checked out the state change examples.

@knut_ny Your solution is very simple and it works every time. I noticed in some of the other debounce examples it would still work incorrectly sometimes. Thanks!