From d36b86929d9c5a9ed8dbe0bc5b445431457a32c5 Mon Sep 17 00:00:00 2001 From: "Tanner Collin (aider)" Date: Thu, 5 Jun 2025 10:50:16 -0600 Subject: [PATCH] feat: Calculate and display RPM every 100ms --- tach/tach.ino | 30 +++++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/tach/tach.ino b/tach/tach.ino index 5057d31..e6f6968 100644 --- a/tach/tach.ino +++ b/tach/tach.ino @@ -5,11 +5,15 @@ #include #include "Adafruit_LEDBackpack.h" // "Adafruit LED Backpack Library" v1.5.0 +#define MEASUREMENT_PERIOD_MS 100 +#define PULSES_PER_REVOLUTION 8 + 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; +unsigned long last_measurement_time = 0; // --- Interrupt Service Routine (ISR) --- void count_pulse() { @@ -43,5 +47,29 @@ void setup() { } 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; + // It's important to re-attach the interrupt as soon as possible + // to minimize missed pulses. + attachInterrupt(digitalPinToInterrupt(TACH_INTERRUPT_PIN), count_pulse, RISING); + + // Calculate RPM + // RPM = (pulses / pulses_per_revolution) / (measurement_period_ms / 1000 / 60) + // RPM = (pulses / pulses_per_revolution) * (60000 / measurement_period_ms) + // 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); + int rpm = (int)rpm_float; + + show(rpm); + Serial.print("Pulses: "); + Serial.print(collected_pulses); + Serial.print(", RPM: "); + Serial.println(rpm); + + last_measurement_time = current_time; + } }