const int irPin = 7;
// =========================================================================
// NOTE: FREQUENCY (Hz) vs. RPM
// - Frequency (Hz) = Cycles (revolutions) per SECOND.
// - RPM = Revolutions per MINUTE.
// - Conversion = Since there are 60 seconds in 1 minute:
// RPM = Frequency (Hz) * 60
// Frequency (Hz) = 1,000,000 us / Period (us)
// RPM = 60,000,000 us / Period (us)
// =========================================================================
// Valid rotation period limits in microseconds:
// 150 us = 6,666 Hz (400,000 RPM max)
// 500000 us = 2 Hz (120 RPM min)
const unsigned long minValidPeriod = 150;
const unsigned long maxValidPeriod = 500000;
// Number of reflective marks or fan blades per full rotation (default = 1)
const int marksPerRev = 1;
const int numSamples = 5;
float smoothedRpm = 0.0;
const float smoothing = 0.25;
unsigned long getMedianPeriod() {
unsigned long samples[numSamples];
int validCount = 0;
for (int i = 0; i < numSamples; i++) {
unsigned long highTime = pulseIn(irPin, HIGH, 250000);
unsigned long lowTime = pulseIn(irPin, LOW, 250000);
unsigned long total = highTime + lowTime;
if (highTime > 50 && lowTime > 50 && total >= minValidPeriod && total <= maxValidPeriod) {
samples[validCount] = total;
validCount++;
}
}
if (validCount == 0) {
return 0;
}
// Sort the valid samples in ascending order to find the median
for (int i = 0; i < validCount - 1; i++) {
for (int j = i + 1; j < validCount; j++) {
if (samples[j] < samples[i]) {
unsigned long temp = samples[i];
samples[i] = samples[j];
samples[j] = temp;
}
}
}
return samples[validCount / 2];
}
void setup() {
Serial.begin(115200);
pinMode(irPin, INPUT);
Serial.println("Nano Pin D7 Tachometer Ready (Hz & RPM)...");
}
void loop() {
unsigned long period = getMedianPeriod();
if (period > 0) {
// 1,000,000 microseconds in 1 second -> gives Frequency in Hz
float frequencyHz = 1000000.0 / (float)period;
// 60,000,000 microseconds in 1 minute (Hz * 60) -> gives speed in RPM
float instantRpm = (60000000.0 / (float)period) / (float)marksPerRev;
if (smoothedRpm == 0.0) {
smoothedRpm = instantRpm;
} else {
smoothedRpm = (smoothing * instantRpm) + ((1.0 - smoothing) * smoothedRpm);
}
Serial.print("Period: ");
Serial.print(period);
Serial.print(" us | Freq: ");
Serial.print(frequencyHz, 1);
Serial.print(" Hz | RPM: ");
Serial.println(smoothedRpm, 1);
} else {
smoothedRpm = 0.0;
Serial.println("Freq: 0.0 Hz | RPM: 0.0");
}
delay(100);
}