refactor: Improve RPM calc using actual elapsed time

This commit is contained in:
2025-06-05 11:16:49 -06:00
parent 17f6c217cd
commit 1f1b379cc2
+13 -3
View File
@@ -64,15 +64,25 @@ void loop() {
// Store the current total snapshot for the next interval's calculation // Store the current total snapshot for the next interval's calculation
g_main_last_pulse_count_snapshot = current_total_snapshot; g_main_last_pulse_count_snapshot = current_total_snapshot;
unsigned long actual_elapsed_time = current_time - last_measurement_time;
// Calculate RPM // Calculate RPM
// RPM = (pulses / pulses_per_revolution) / (measurement_period_ms / 1000 / 60) // RPM = (pulses / pulses_per_revolution) / (actual_elapsed_time_ms / 1000 / 60)
// RPM = (pulses / pulses_per_revolution) * (60000 / measurement_period_ms) // RPM = (pulses / pulses_per_revolution) * (60000 / actual_elapsed_time_ms)
// Ensure floating point division for accuracy before converting to int for display // Ensure floating point division for accuracy before converting to int for display
float rpm_float = ( (float)collected_pulses / PULSES_PER_REVOLUTION ) * (60000.0 / MEASUREMENT_PERIOD_MS); float rpm_float = 0.0;
if (actual_elapsed_time > 0) { // Avoid division by zero
rpm_float = ( (float)collected_pulses / PULSES_PER_REVOLUTION ) * (60000.0 / actual_elapsed_time);
}
int rpm = (int)rpm_float; int rpm = (int)rpm_float;
show(rpm); show(rpm);
// Debugging output
Serial.print("Pulses: "); Serial.print(collected_pulses);
Serial.print("\tElapsed ms: "); Serial.print(actual_elapsed_time);
Serial.print("\tRPM: "); Serial.println(rpm);
last_measurement_time = current_time; last_measurement_time = current_time;
} }
} }