Pages: [1]   Go Down
Author Topic: Counting Button Presses  (Read 1336 times)
0 Members and 1 Guest are viewing this topic.
0
Offline Offline
Sr. Member
****
Karma: 0
Posts: 250
Arduino is the brain of the robot.
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

I know that this is probably very easy code.. but I want to be able to print how many times a button has best pressed within 5 seconds. For example, if i press a button 7 times within a 5 seconds time frame, it will print, "the button has been pressed 7 times....
Logged

Seattle, WA USA
Offline Offline
Brattain Member
*****
Karma: 634
Posts: 50243
Seattle, WA USA
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Within any given 5 seconds? Or does the 5 second window start when the button is first pressed?

In other words, once the button is pressed, do nothing else for 5 seconds except count button presses?
Logged

0
Offline Offline
Sr. Member
****
Karma: 0
Posts: 250
Arduino is the brain of the robot.
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

The first time the button is pressed is when the five seconds starts, and then when the five seconds is over, it will stop. then repeat...
Logged

Seattle, WA USA
Offline Offline
Brattain Member
*****
Karma: 634
Posts: 50243
Seattle, WA USA
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Code:
long firstPress = 0;
long countingTime = 5000;
int presses  = 0;
int buttonPin = 3; // Or whatever...

void loop()
{
   if(digitalRead(buttonPin) == HIGH)
   {
       firstPress = millis();
       presses = 1;
       while(millis() - firstPress < countingTime)
       {
           if(digitalRead(buttonPin) == HIGH)
           {
               presses++;
           }
       }
   }

   // Do something about the button presses...
}

Some delay after each digitalRead returned HIGH will most likely be needed, to prevent button bounce inaccuracies from affecting the count, but this is the general idea. Keep the delay small - 5 milliseconds, or so.
  
Logged

Pages: [1]   Go Up
Jump to: