How to determine how long a button is pressed

I need to determine how long a button is pressed (held closed).

1 second produces a single beep 2 seconds produces a second beep etc.

Is anyone able to help please?

Cheers

Have a look at the code in this Thread and in this Thread

…R

In the Arduino Reference page https://www.arduino.cc/en/Reference/HomePage

under Time you will find the millis() function that returns an unsigned long value == milliseconds since startup.

The unsigned part is important because when you subtract a past millis from a later millis the difference will always be right up to the largest amount the unsigned variables can hold --- even across rollover, always right.

With unsigned long milliseconds the longest difference you can time is just over 49.7 days and it takes that long to roll the counter back past zero, again not a problem as long as the interval is not longer.

That known, you can save the value of millis() at any time, like when a button is pressed, and later subtract that from the current millis() and get milliseconds between time difference.

The thread that Robin gave you link to is a much longer and more full tour of the subject full of ways and whys. I have 3 Nick Gammon addresses in my signature space below to very well made tutorials on the subject as well.

The thing is that you don't need to cover all of that just to get time differences. Those cover the more important matter of blocking code and not blocking when you want to run fast which is essential to doing things very closely on time but less so (though still highly desirable) in your case.