Important changes to forums and questions
All forums and questions are now archived. To start a new conversation or read the latest updates go to forums.mbed.com.
10 years, 11 months ago.
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(); printf("RPM_t: %f\r\n", _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
2 Answers
10 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.
10 years, 11 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 ;)