const byte IR_PIN = 7;
const unsigned long SERIAL_BAUD = 115200;
const unsigned long MICROSECONDS_PER_SECOND = 1000000UL;
const float SECONDS_PER_MINUTE = 60.0f;
const unsigned long MIN_VALID_PERIOD_US = 150UL;
const unsigned long MAX_VALID_PERIOD_US = 500000UL;
const unsigned long PULSE_TIMEOUT_US = 300000UL;
const unsigned long MIN_PHASE_US = 50UL;
const byte MARKS_PER_REV = 1;
const byte NUM_SAMPLES = 5;
const float RPM_SMOOTHING = 0.25f;
const unsigned long LOOP_DELAY_MS = 100UL;
const byte DISPLAY_DECIMAL_PLACES = 1;
const unsigned long NO_PERIOD_US = 0UL;
const byte NO_VALID_SAMPLES = 0;
const byte EVEN_REMAINDER = 0;
const float ZERO_RPM = 0.0f;
float smoothedRpm = ZERO_RPM;
unsigned long getMedianPeriodUs() {
unsigned long samples[NUM_SAMPLES];
byte validCount = NO_VALID_SAMPLES;
for (byte i = 0; i < NUM_SAMPLES; i++) {
unsigned long highTime = pulseIn(IR_PIN, HIGH, PULSE_TIMEOUT_US);
unsigned long lowTime = pulseIn(IR_PIN, LOW, PULSE_TIMEOUT_US);
if (highTime == NO_PERIOD_US || lowTime == NO_PERIOD_US) {
continue;
}
if (highTime <= MIN_PHASE_US || lowTime <= MIN_PHASE_US) {
continue;
}
unsigned long period = highTime + lowTime;
if (period >= MIN_VALID_PERIOD_US &&
period <= MAX_VALID_PERIOD_US) {
samples[validCount] = period;
validCount++;
}
}
if (validCount == NO_VALID_SAMPLES) {
return NO_PERIOD_US;
}
// Sort valid measurements from smallest to largest.
for (byte i = 0; i < validCount - 1; i++) {
for (byte j = i + 1; j < validCount; j++) {
if (samples[j] < samples[i]) {
unsigned long temp = samples[i];
samples[i] = samples[j];
samples[j] = temp;
}
}
}
byte middle = validCount / 2;
if (validCount % 2 == EVEN_REMAINDER) {
byte lowerMiddle = middle - 1;
unsigned long difference = samples[middle] - samples[lowerMiddle];
return samples[lowerMiddle] + difference / 2;
}
return samples[middle];
}
void setup() {
Serial.begin(SERIAL_BAUD);
pinMode(IR_PIN, INPUT);
Serial.println(F("Nano D7 tachometer ready"));
}
void loop() {
if (MARKS_PER_REV == 0) {
Serial.println(F("Error: MARKS_PER_REV must be greater than zero"));
delay(LOOP_DELAY_MS);
return;
}
unsigned long periodUs = getMedianPeriodUs();
if (periodUs == NO_PERIOD_US) {
smoothedRpm = ZERO_RPM;
Serial.println(F("No valid signal"));
delay(LOOP_DELAY_MS);
return;
}
float frequencyHz =
static_cast<float>(MICROSECONDS_PER_SECOND) /
static_cast<float>(periodUs);
float instantRpm =
(frequencyHz * SECONDS_PER_MINUTE) /
static_cast<float>(MARKS_PER_REV);
if (smoothedRpm == ZERO_RPM) {
smoothedRpm = instantRpm;
} else {
smoothedRpm =
RPM_SMOOTHING * instantRpm +
(1.0f - RPM_SMOOTHING) * smoothedRpm;
}
Serial.print(F("Period: "));
Serial.print(periodUs);
Serial.print(F(" us | Frequency: "));
Serial.print(frequencyHz, DISPLAY_DECIMAL_PLACES);
Serial.print(F(" Hz | RPM raw: "));
Serial.print(instantRpm, DISPLAY_DECIMAL_PLACES);
Serial.print(F(" | RPM smoothed: "));
Serial.println(smoothedRpm, DISPLAY_DECIMAL_PLACES);
delay(LOOP_DELAY_MS);
}