# Counting pulse in firmware without interrupt

How can I count the number of pulses using a microcontroller (any), provided the following conditions:

1. Can not use any interrupt (no interrupt on pin change allowed)
2. Can not use any of uC's hardware features (counter, timer etc.)

The width of the pulse is random and can not be predicted in advance. This pulse train is given to one of the general purpose IO pins. The solution should be purely software based ( C/assembly).

The software debouncing method which reads pin status as a series of 0's and 1's is a possible option but you need to hardcode the transition pattern, which means that you need to know the pulse width in advance and hence its can not be accepted.

Any idea?

PS: This question was asked on a technical interview with one of the major automotive component supplier.

• Is your code the only thing executed? Because if not, it won't be possible. If not, then you can just do something like - add 1 - read gpio - add 1 - read gpio... and figure out how many clock cycles this takes. – NeinDochOah Jan 23 '16 at 16:14
• Without hardware timer, counter and without interrupt this is not possible. And even if you would poll the GPIO status each scan makes this useless, since you would require all resources of a MCU to count pulses with no guarantee to catch all of them. – Marko Buršič Jan 23 '16 at 16:15
• @Nein... yes that should be a reasonable assumption. – HKL Jan 25 '16 at 4:03

We have to assume that "it's impossible" is not the right answer, so that means that we can assume that the CPU has enough power to poll the pin at a rate that's fast enough not to miss any pulses.

I don't know why you think that "you need to hardcode the transition pattern". All you need to do is find the 0→1 and 1→0 transitions and count one or the other. The only thing required is to keep track of the previous state of the pin.

In pseudocode:

count = 0;