Creating a counter together with a timer

Hey folks,

I want to know how I can count the numbers of HIGH inputs (from a outside source, e.g. button) within a timeframe of around 1000ms.

Let's say I press a button three times within 1 second, how do I let arduino count that number of presses and connect a function to it?

I've been looking for the implementation of the millis() and counter() functions, but I don't really get how they work.

Could someone enlighten me in this matter?

Thanks!

Roy
(experience: novice)

how do I let arduino count that number of presses and connect a function to it?

Can you clarify what you mean by "connect a function to it"?

Well, for instance, turn a LED on for 5 seconds.

I suggest you go to the "Learning" section of the website and look at the button state change example among others, this might be the kind of thing you are after.

Yeah, I know the button state change detection. I just need to count the number of presses within 1000ms. I don't know how to implement the timer (using the arduino clockcycles, pref.) together with the counter...

I don't know how to implement the timer

The timer is created for you - use "millis".

What "starts" the 1000ms?
The first press?
Or is it a rolling "second"?

I receive 1 HIGH input. That should start a timer function that runs for 1000ms. Together with the timer, the counter should start which records how many presses are received. The counter should store that amount of presses.

When the timer reaches 1000ms, both the timer and the counter stop.

Then, the code checks how many presses were registered and starts a function (like put led1 on) that comes with that specific number of presses (so: If 2 presses: function2, If 3 presses: function3 etc etc)

I hope this clarifies some...

Thanks for the reactions.

Pseudo code.

while (button == LOW) {}; // wait for the pin to go HIGH
timeNow = millis ();
while (timeNow + 1000 > millis ()) {
count_button_presses ();
}
switch (the_number_of_presses) {
case 0: // do something
break;

case 1: // do something else
break;

// and so on.
}

You may want to use the following mod the the pseudo code posted above so that timer rollover wont be a problem

startTime = millis ();
while (millis() - startTime < duration) {

Thanks! That'll help :slight_smile: