Best practice for pulse counting - how to implement time as a constant/overflow

Hi everyone,

I need a best practice advice. I need count pulses arriving at one pin. Super simple, yes? The source is a liquid flow monitor. The pulses per gallon are well known so the issue here isn't around math. It is around best practice.

I figured I can simply increment a counter with each pulse which will give me liquid dispensed since boot. That's just fine, but what about overflow? Eventually the counter will overflow, what is the best practice advice around this?

My second question is around involving time - if I would like to have PPM for example saved in a variable which could can be sent out via the serial port every 5 seconds or so, would you point me to some examples.

So in summary, I need to know total liquid dispensed so far in absolute terms and also a time driven PPM measure

Thank you ~B

It is easy to detect overflow. If the counter is a signed integer, check for change of sign after you increment. If the counter is unsigned, check the result for zero after increment.

Take appropriate action and increment a second variable to keep track of overflows.

If you use a large enough data type (e.g. long integer) overflow would be unlikely in real life situations.

@jremington Thank you for your reply. Any example code spinets will be appreciated, including the basics, how do you detect efficiently positive edge, what't the best practice around GPIO pin detection, I would guess endlessly "polishing" the pin and looking for state change isn't the way to go?

Maybe a quick example of an interrupt routine which fires at edge change? That kind of programming stuff, I am terrible at it,

I do know the theory and the bare metal mechanics but where I have trouble is expressing all that knowledge into good practice efficient code :)

Thank you ~B

You say that "pulses per gallon are well known" but you don't say what the value is. If we assume a very high number, like 1000, using an 'unsigned long' counter would still get you 4.2 million gallons. Would that be sufficient for the expected life of your device? Are the device pulses well conditioned or will you need to debounce? What is your maximum expected flow rate? How does that translate to pulses per second?

You need to provide details of the expected flowmeter output: logic levels, timing of pulses, measurement period, etc.

Post a link to the flowmeter data sheet or product page.

Totally, here's the sensor:

Please state expected maximum and minimum flow rates in your application.

@jremington this is a gravity fed thing so likely 5 GPM at most with a 1/2 pipe

You can count pulses by adding a counter to the State Change Detection example that ships with the IDE.