Better way to avoid duplicated printing?

Hi all,

i intent to print a statement when push button is pushed,

I am referring the example code under Button criteria that come with the arduino software.

Below is my attempt my this purpose. Somehow i noticed duplicate printing occurs at sometime.

I believe there is better way to do the same thing..

Hope to have your advise.

Many thanks.

// constants won't change. They're used here to 
// set pin numbers:
const int buttonPin = 2;     // the number of the pushbutton pin
const int ledPin =  13;      // the number of the LED pin

// variables will change:
int buttonState = 0;         // variable for reading the pushbutton status
int i;
boolean showed;

void setup() {
  // initialize the serial communication baud rate
  Serial.begin(19200);
  // initialize the LED pin as an output:
  pinMode(ledPin, OUTPUT);      
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);     
  i=1;
  showed=false;
  
  Serial.println("==========Start==========");
}

void loop(){
  // read the state of the pushbutton value:
  buttonState = digitalRead(buttonPin);

  // check if the pushbutton is pressed.
  // if it is, the buttonState is HIGH:
  if (buttonState == HIGH) {     
    // turn LED on:    
    digitalWrite(ledPin, HIGH);  
    
    if(showed==false){
       Serial.print(i);
       Serial.print("\t");
       Serial.println("Button is pressed.");
    }
    showed=true;
    i++;   
  } 
  
  else{
     digitalWrite(ledPin, LOW);  
     showed = false;
  }
     
}

Your problem is that the button is a mechanical switch. When you press it, the contacts connect and disconnect many times during what seems to you like one quick press. You need to "debounce" the button. Debouncing is the term used to describe making one button press truly look like just one button press instead of several.

You can do it in hardware by putting a 680pF capacitor between the active side and ground. Or you can do it in software. Look for a library called Bounce:

http://www.arduino.cc/playground/Code/Bounce

I would look for a transition (ie. is now high but was low) and throw in a debounce (say, 20 mS).

eg.

  if (buttonState == HIGH && oldButtonState == LOW) 
    {     
    delay (20);
     // blah blah

    }  // end of button pressed

  oldButtonState = buttonState;

Thank you for yours reply and advise.

I am trying it the coding..

will update here again with my finding!

Thank you so much!