I would like to know if there is a way to count digital pulses on an Arduino WITHOUT implementing an interrupt routine.
Further description: I have a sensor that outputs digital pulses proportional to some measurement I want to calculate.
Not only can you do it without an interrupt handler, you can do it little or no software and handle faster pulse rates that is possible by software polling or interrupt counting.
The Atmel AVR that most Arduinos are based on have counter/timer hardware that will count pulsed in an input pin directly. All you have to do is configure the hardware for counter operation and read the counter register. There is a small complexity for 16 bit counters on an 8 bit device, but that is simple to overcome. Arduino configures timers for default PWM operations, but that can be overridden as described here(See the AVR user manual for more detail) - you need to use the timer/counter in CTC mode.
ARM based Arduninos and pretty much any other microcontroller will have similar hardware facilities; some have greater flexibility over which pins may be used for hardware counting.
On the AVR you have 8 and 16 bit counters, if you need larger counts you may have to handle the overflow interrupt. If you will be polling the counter regularly, you may be able to handle even that without interrupts while being able to poll at a much lower and possibly aperiodic rate than the rate of input pulses simply by polling the overflow flag before the next overflow.
In your case, you probably need to read the pulse count at a regular period that shorter than the time in which the counter will overflow at the maximum expected pulse rate. So for example if you were using an 8 bit counter and the maximum pulse rate were 1KHz you would need to poll every 256/1000 seconds or shorter, but the greatest precision is afforded by making the period as long as possible. So for example you might have something like the following (this is not real code, and only a fragment):
for(;;)
{
delayMS( 250 ) ;
frequency = 4 * readCounter() ;
}
An alternative that will get a better linear response but non-deterministic readout would be to poll the overflow flag, and measure the time taken to count a fixed number of pulses and so determine your measurement from the time for a fixed count rather than the count for a fixed time.
for(;;)
{
int start = getMillisec() ;
while( !counterOVF() )
{
// Do nothing (or something useful but quick)
}
int t = getMillisec() - start ;
frequency = 256 * t / 1000 ;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With