Instructables

Is there a way to count button pushes on an arduino and have it reset the count at a certain number?

I would like to count the number of buttons pushed and when it reaches the number 8, I would like it to reset it to 0. Can anyone help me with an example code or a tutorial somewhere? Greatly Appreciated!

Take the button sketch. Add a counting variable. If the button is pressed add 1 to that variable. If the variable is >= 8 store 0 to the counting variable.

const int buttonPin = 2;     // the number of the pushbutton pin
const int ledPin =  13;      // the number of the LED pin
int count = 0;               // Count the button presses

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

void setup() {
  // initialize the LED pin as an output:
  pinMode(ledPin, OUTPUT);     
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);    
}

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); 
    count++;               // add 1 to the count
    if (cout >= 8) {
      count = 0;
    } 
  }
  else {
    // turn LED off:
    digitalWrite(ledPin, LOW);
  }
}
if (buttonState == HIGH) {   
    // turn LED on:  
    digitalWrite(ledPin, HIGH);
    count++;               // add 1 to the count
    if (cout >= 8) {
      count = 0;
   while(buttonState==HIGH); //wait here.
    }
  }
bigjohn412 (author) 1 year ago
Ok, I understand now. Thanks!
Careful, that sketch has a fatal flaw.
How many iterations of loop() happen while the button is pressed?
1000 ?
Yep...
count ++

And...

if (count >= 8 ) {

Missing a space between count and the ++. Also forgot the 'n' in count on the if statement. Should have proof read and compiled the sketch before posting.

There are many ways to structure it depending on the exact needs for the sketch. But you get the general idea of adding a means of tracking things. Create the variable for tracking, add to the variable where needed and form time to time query that variable to see if it's reached the mark you want. 
You need a state to catch the fact the button STAYS pressed. What you want to count is the state off-on-off