#include <Arduino.h>
volatile uint16_t lastCapture = 0;
volatile uint32_t totalTicks = 0;
volatile uint16_t pulseCount = 0;
volatile uint8_t overflowCount = 0;
volatile bool firstPulse = true;
unsigned long lastSerialUpdate = 0;
const unsigned long serialInterval = 250; // Print every 250 ms
float smoothedHz = 0;
void setup() {
Serial.begin(115200);
Serial.println("Tach-Attack Ultra-Smooth Ready");
// Configure Timer1: Normal mode, Prescaler 8 (2,000,000 ticks/sec)
noInterrupts();
TCCR1A = 0;
TCCR1B = (1 << CS11); // Prescaler 8 (0.5 us per tick)
TIMSK1 = (1 << TOIE1); // Overflow every 32.768 ms
TCNT1 = 0;
interrupts();
pinMode(2, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(2), pulseISR, FALLING);
}
ISR(TIMER1_OVF_vect) {
if (overflowCount < 255) {
overflowCount++;
}
}
void pulseISR() {
uint16_t now = TCNT1;
if (firstPulse || overflowCount > 1) {
// Sync starting point without recording a bad partial period
lastCapture = now;
overflowCount = 0;
firstPulse = false;
return;
}
// Unsigned 16-bit subtraction automatically handles single timer wrap-arounds
uint16_t dt = now - lastCapture;
lastCapture = now;
overflowCount = 0;
// Accumulate ticks and pulse count directly in hardware ticks
totalTicks += dt;
pulseCount++;
}
void loop() {
if (millis() - lastSerialUpdate >= serialInterval) {
lastSerialUpdate = millis();
// Safely grab and reset accumulated values atomically
noInterrupts();
uint32_t ticks = totalTicks;
uint16_t count = pulseCount;
uint8_t ovf = overflowCount;
totalTicks = 0;
pulseCount = 0;
interrupts();
if (ovf > 2 || count == 0) {
firstPulse = true;
smoothedHz = 0;
Serial.println("Hz: 0.0 (SLOW!)");
} else {
// Average frequency across all pulses in the 250 ms window
float windowHz = (2000000.0 * count) / ticks;
// Optional: Light exponential blend for rock-solid display stability
if (smoothedHz == 0) {
smoothedHz = windowHz;
} else {
smoothedHz = (smoothedHz * 0.5) + (windowHz * 0.5);
}
Serial.print("Hz: ");
Serial.println(smoothedHz, 1);
}
}
}