## Why would a timer value be different when printed?

I have an interrupt that measures time between spark pulses and calculates rotations. Problem is if I don't print the time, the value is way off. What's the deal?

#### With printf

```// RPM Interrupt
void RPM_Sensor::rpm_pickup() {
if (++counter >= 1) {
// Time = time / counter
// Hertz = 1 / Time
// RPM = 60 * Hertz
rpm = 60 * counter / _rpm_timer.read();
_rpm_timer.reset();
counter = 0;
}
}
```

#### Without printf

```void MPH_Sensor::mph_pickup() {
if (++counter >= 1) {
mph = (uint32_t)(60 * counter / _mph_timer.read());
_mph_timer.reset();
counter = 0;
}
}
```

Below I have a 1Hz(60 RPM) output hooked up to RPM, then I move it to MPH.

#### Output

```RPM_t: 0.983295
MPH: 0, RPM: 61
MPH: 0, RPM: 61
MPH: 0, RPM: 61
RPM_t: 0.783659
MPH: 0, RPM: 76
MPH: 0, RPM: 76
MPH: 0, RPM: 76
MPH: 0, RPM: 76
MPH: 0, RPM: 76
MPH: 14996, RPM: 76
MPH: 14996, RPM: 0
MPH: 14996, RPM: 0
MPH: 14996, RPM: 0
MPH: 14996, RPM: 0
MPH: 14996, RPM: 0
MPH: 14996, RPM: 0
```

##### 7 years, 10 months ago.

Hi Eric, I think with printing you first read the timer and calculate and then you read it a second time and print the second value. Try to read the timer just once and save this value for later printing.

Well not sure how, but I set a variable with the time before using it and that seemed to do the trick.

posted by Eric Fossum 04 Feb 2014
##### 7 years, 10 months ago.

Is counter an integer? It might be that your calculation is off due to where it uses integers and where floats. Especially since at the first one you don't have your explicit conversion to integer. So I would try:

```mph = (uint32_t)(60.0f * (float)counter / _mph_timer.read());
```

If counter isn't an integer, it should be one ;)

I will try that a little later today, but I don't think it'll work. As I watch the 15000 values go by, a 60 will appear at random about once every 50 bad values.

posted by Eric Fossum 17 Jan 2014

Could you also post how those functions are called?

posted by Erik - 17 Jan 2014

BTW: You really shouldn't put print statements inside interrupt routines.

posted by Kevin Braun 17 Jan 2014