diff --git a/tach/tach.ino b/tach/tach.ino index fefdf1c..ffffc55 100644 --- a/tach/tach.ino +++ b/tach/tach.ino @@ -12,12 +12,13 @@ Adafruit_7segment matrix = Adafruit_7segment(); // --- Tachometer variables --- 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; // --- Interrupt Service Routine (ISR) --- void count_pulse() { - pulse_count++; + g_isr_pulse_count_total++; } void show(int num) { @@ -50,10 +51,18 @@ void loop() { unsigned long current_time = millis(); if (current_time - last_measurement_time >= MEASUREMENT_PERIOD_MS) { - detachInterrupt(digitalPinToInterrupt(TACH_INTERRUPT_PIN)); - unsigned long collected_pulses = pulse_count; - pulse_count = 0; - attachInterrupt(digitalPinToInterrupt(TACH_INTERRUPT_PIN), count_pulse, RISING); + unsigned long current_total_snapshot; + + // Atomically read the total pulse count + 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 // RPM = (pulses / pulses_per_revolution) / (measurement_period_ms / 1000 / 60)