Measurement Computing   Easy to Use | Easy to Integrate | Easy to Support catalog banner

How to use a digital input to count events (programatically)

Expand / Collapse

How to use a digital input to count events (programatically)

A common question is, "How do I use a digital input to count events?"

This question is asked regarding the following products (not a definitive list):

And any analog Input or output boards with additional DIO capabilites.

Here is an explanation in pseudo-code, telling the programming process:

These devices do not contain the capability to count pulses (well they do, but just 1 channel), only to tell you if something is on or off.

You would be better off to use something like a USB-QUAD08 which has that capability built in.


Barring that, you would need to use a timer that clocks at least twice as often as the button can be pressed.  This is so you do not miss button press events.

The way to get it not count more than once per button press is to keep track of the last position of the button.  For example, let’s say the button is 0 when off and 1 when pressed.


At the initial timer tick, the digital Input/button would read 0 (not pressed), and would stay that way until someone presses the button. You read the value, and copy it to a variable called ‘Last’


At some time index in the future, someone presses the button, and it becomes a 1 (pressed) read by the digital input.

You would compare it to the ‘Last’ reading, if the last reading is set to 0 and the current reading is 1, then you increment your counter (by one) and update the 'Last' variable to be 1.

Next iteration of the Timer Tick, you still see a 1 for that input, comparing it to the ‘Last’ reading of 1, you know it has not been released yet so you do NOT increment your counter, and don’t update Last.


At the following iteration of Timer Tick, the input is back to 0, now you can update the 'Last' variable to be 0 again, and wait for the cycle to repeat.

So in this method, you only increment your counter when the value of 'Last' is 0.

In Summary, you only increment the counter when 'Last' and current readings are 0 and 1 respectively, not when they are both 1, and not when 'Last' is 1, and current reading is 0.

Get it?

This technique can be used for any number of digital Inputs, and for virtually any programming language.

Rate this Article:

Add Your Comments

For comments email [email protected].

Article ID: 50355

Last Modified:4/23/2012 3:10:30 PM

Article has been viewed 3,835 times.