-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFanController.cpp
More file actions
58 lines (47 loc) · 1.34 KB
/
FanController.cpp
File metadata and controls
58 lines (47 loc) · 1.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include "FanController.h"
FanController::FanController(int pwm, int tach)
: pwmPin(pwm), tachPin(tach), tachCounter(0), lastPulseTime(0), rpm(0), pwmValue(255) {}
void FanController::setup() {
pinMode(pwmPin, OUTPUT);
pinMode(tachPin, INPUT_PULLUP);
analogWrite(pwmPin, pwmValue);
}
void FanController::setPWM(int value) {
pwmValue = constrain(value, 0, 254); // At 255, some fans stop sending valid TACH signals — temporary limit is 254
analogWrite(pwmPin, pwmValue);
}
void FanController::pulseDetected() {
unsigned long now = micros();
if (now - lastPulseTime > 1000) { // debounce to ignore noise
tachCounter++;
lastPulseTime = now;
}
}
void FanController::measureRPM() {
noInterrupts();
unsigned long count = tachCounter;
tachCounter = 0;
interrupts();
if (count < 5) {
rpm = 0;
} else {
rpm = (count * 60) / 2; // Assuming 2 pulses per revolution
}
updateSmoothedRPM(rpm);
}
void FanController::printStatus() {
Serial.print("Fan RPM: ");
Serial.println(rpm);
}
void FanController::updateSmoothedRPM(int newRPM) {
rpmBuffer[bufferIndex] = newRPM;
bufferIndex = (bufferIndex + 1) % SMOOTHING_WINDOW;
int sum = 0;
for (int i = 0; i < SMOOTHING_WINDOW; i++) {
sum += rpmBuffer[i];
}
rpmSmoothed = sum / SMOOTHING_WINDOW;
}
int FanController::getSmoothedRPM() {
return rpmSmoothed;
}