Debounce question from a real beginner

Trying to write a code that will count as I press a button. I have my button connected on pin 8. I have the following code which works except it needs a debounce. I've tried for a while to add one in and maybe I'm putting things in the wrong place or something but nothing seems to work for me. Here's my code, can anyone please help by writing in some debouncing code?

int state=LOW;
int lastState=LOW;
int count=0;
void setup()
{
Serial.begin(9600);
pinMode(8, INPUT);
state=digitalRead(8);
}
void loop()
{
if (state==HIGH && lastState==LOW)
{
count++;
Serial.println(count);
}
lastState=state;
state=digitalRead(8);
}

Moderator edit: Code reposted, sans smilies

Well first off post your code in a box. Modify that post, select the code and hit the # icon and save. You might also want to correct the smiles.

All you need to is to add a delay after a change is detected.

int state=LOW;
int lastState=LOW;
int count=0;
void setup()
{
Serial.begin(9600);
pinMode(8, INPUT);
}

void loop()
{
state=digitalRead(8);
if (state != lastState)
 { 
   delay(30);  // debounce delay
   state=digitalRead(8);  // read again in case of false initial reading
 }

if (state==HIGH && lastState==LOW)
{
count++;
Serial.println(count);
}
lastState=state;

}

Thank you sir. Worked perfect. :slight_smile: