Best way to approach this 'problem'

Hi, im working on a project. I'll explain the short, relevant version.

I have a variable that stores counted pulses

unsigned long pulseCount = 0

and a variable that stores my desired sample time in milliseconds

unsigned long sample_time = 10000 //10 seconds
unsigned long sample_time = 120000 //2min

My target unit is pulses per second, alwasy in complete numbers, no decimals (555 not 555.5)

for this i use:

int ppmin = pulseCount * (60000 / sample_time)

this works fine for times >1min. If greater than 1min, the value inside the () becomes <1 which will create alsways 0 for ppmin !

So is the best way to use float for ppmin and then convert the float back to an int? or what should i do here?

Do the brackets the other way. Multiply first, then divide.

Make sure that you don't overflow the int when multiplying. Suddenly an int looks really small when you multiply by 60000. Use unsigned longs, which you can get by just putting "UL" at the end of the constant, eg: 6000UL or use an explicit cast: (unsigned long)60000

Then double-check that your largest possible value will fit in an unsigned long. If you are counting very large numbers then you may need a 64-bit long long.

Thanks, this works! :slight_smile:

No problem about the long, since the max value (hardware limit) ist 666k pulse per minute, this fits good in a long! :slight_smile: