Toggle a led with a switch My code:

const int buttonPin = 2;     // the number of the pushbutton pin
const int ledPin =  13;      // the number of the LED pin

bool buttonState = 0;         // variable for reading the pushbutton status
bool ledState = 0;
void setup() {
  pinMode(ledPin, OUTPUT);   // initialize the LED pin as an output:
  pinMode(buttonPin, INPUT); // initialize the pushbutton pin as an input:
}
void loop() {
  buttonState = digitalRead(buttonPin);// read the state of the pushbutton value:
  if (buttonState == HIGH) 
 {        
  ledState = !ledState;
 }
  if (ledState == HIGH) 
 {             
   digitalWrite(ledPin, HIGH); // turn LED on: 
 }
   else 
 {
    digitalWrite(ledPin, LOW); // turn LED off:
 }
}


So this is supposed to toggle a led's light on and off. currently it does do that but its not always the case. Currently, if the button is pressed on the arduino board, it has a 50-50 chance of changing its state. What part of the code is leading to this outcome?
If you're connecting the button from pin 2 to ground and not using an external pull-up, it can lead to trouble. Either use an external pull-up or set the internal one:

pinMode(buttonPin, INPUT_PULLUP); // initialize the pushbutton pin as an input:


Also, you need to debounce the button.