debouncing

I am a beginner in arduino. Just wrote a code wherein whenever you press the switch the state of the LED changes. But, sometimes even after pressing the button its state doesn't change i.e. it is not working smoothly (kept check of debouncing using delay). Would be helpful if someone could point out the mistake

int ledpin = 2;
int button = 8;
int val;
//int prevval = 0;
int state = LOW;

void setup() {
Serial.begin(9600);
pinMode(ledpin, OUTPUT);
pinMode(button, INPUT);
// digitalWrite(ledpin, LOW);
}

void loop() {
//delay(200);
int val = digitalRead(button);
delay(200);
Serial.println(val);

if(val == HIGH ){
state = !state;
digitalWrite(ledpin, state);
}

val=LOW;

}

Would be helpful if someone could point out the mistake

"The" mistake is an assumption that is not valid. "The mistakes" is what you meant to say.

  1. You failed to post your code correctly.
  2. You failed to include a schematic, leading me to assume that you failed to wire your switch correctly.
  3. You littered your code with delay()s. That is a BAD habit to start with. STOP THAT!

You are only checking the button ever 200 milliseconds. If you have a short press (< 200 milliseconds) you may miss the press completely. If you have a long press (> 200 milliseconds) you may count that press two or three times.

See the example at: File->Examples->02.Digital->Debounce

  int val = digitalRead(button);
  delay(200);

That does not debounce your switch. The only thing that that does is slow the program down. See the debounce reference page to see how to properly use software debounce.