Push button code error - plz help

I'm trying to display values 1,2,3,4 on serial monitor whenever I press the push button once. I used if switch condition for that. But I can only print 1,3 each time I press and leave the pushbutton. if I hold the push button, its printing 2,4 too. but if I leave it only prints 1,3.

below is my code. plz help. I found if I use a switch instead of push-button, it works good, with all 4 numbers 1,2,3,4 printing.

int but_state=0; int sel=1;

void setup()

{ Serial.begin(9600); //pinMode(12,INPUT); pinMode(12,INPUT_PULLUP);

but_state=digitalRead(12); delay(5000); }

void loop() {

if(digitalRead(12)!=but_state) { but_state=digitalRead(12);

if(sel==4) { sel=1; }

else { sel++; }

}

switch(sel) {

case 1 : Serial.println("1"); break;

case 2 : Serial.println(" 2"); break;

case 3 : Serial.println(" 3"); break;

case 4: Serial.println(" 4"); break; }

}

I think you experience boucing effect Try adding a delay(30) instruction after but_state=digitalRead(12); in the loop

  if (digitalRead(12) != but_state)

This tests whether the button state has changed. In order to act only when the button becomes pressed you also need to test whether it is in that state after the change

sir, could you plz elaborate on how to do that, as im new to coding.

Something like this

previousButtonState = buttonState;
buttonState = digitalRead(buttonPin);
if (buttonState != previousButtonState and buttonState == LOW) { // assumes LOW when pressed
  // do stuff

...R

Note how Robins code reads the state of the input and saves it in a variable to avoid the need to read the state a second time in the test ?

"REPORT TO MODERATOR" is not a reply button LOL

Bob.

Hi, Welcome to the forum.

Please read the first post in any forum entitled how to use this forum. http://forum.arduino.cc/index.php/topic,148850.0.html . Then look down to item #7 about how to post your code. It will be formatted in a scrolling window that makes it easier to read.

Can you please post a copy of your circuit, in CAD or a picture of a hand drawn circuit in jpg, png?

Thanks.. Tom... :)