fix: Improve pulse counting with continuous ISR and diff

This commit is contained in:
2025-06-05 11:11:02 -06:00
parent 6ec278e97d
commit 17f6c217cd
+15 -6
View File
@@ -12,12 +12,13 @@ Adafruit_7segment matrix = Adafruit_7segment();
// --- Tachometer variables --- // --- Tachometer variables ---
const int TACH_INTERRUPT_PIN = A0; // Or any other digital pin capable of interrupts const int TACH_INTERRUPT_PIN = A0; // Or any other digital pin capable of interrupts
volatile unsigned long pulse_count = 0; volatile unsigned long g_isr_pulse_count_total = 0; // ISR increments this continuously
unsigned long g_main_last_pulse_count_snapshot = 0; // Main loop stores previous snapshot here
unsigned long last_measurement_time = 0; unsigned long last_measurement_time = 0;
// --- Interrupt Service Routine (ISR) --- // --- Interrupt Service Routine (ISR) ---
void count_pulse() { void count_pulse() {
pulse_count++; g_isr_pulse_count_total++;
} }
void show(int num) { void show(int num) {
@@ -50,10 +51,18 @@ void loop() {
unsigned long current_time = millis(); unsigned long current_time = millis();
if (current_time - last_measurement_time >= MEASUREMENT_PERIOD_MS) { if (current_time - last_measurement_time >= MEASUREMENT_PERIOD_MS) {
detachInterrupt(digitalPinToInterrupt(TACH_INTERRUPT_PIN)); unsigned long current_total_snapshot;
unsigned long collected_pulses = pulse_count;
pulse_count = 0; // Atomically read the total pulse count
attachInterrupt(digitalPinToInterrupt(TACH_INTERRUPT_PIN), count_pulse, RISING); noInterrupts();
current_total_snapshot = g_isr_pulse_count_total;
interrupts();
// Calculate pulses collected during this interval
unsigned long collected_pulses = current_total_snapshot - g_main_last_pulse_count_snapshot;
// Store the current total snapshot for the next interval's calculation
g_main_last_pulse_count_snapshot = current_total_snapshot;
// Calculate RPM // Calculate RPM
// RPM = (pulses / pulses_per_revolution) / (measurement_period_ms / 1000 / 60) // RPM = (pulses / pulses_per_revolution) / (measurement_period_ms / 1000 / 60)