#define FAN_WIRES 4 #define PWM_PIN 3 #define SENSOR_PIN 2 #if FAN_WIRES == 4 volatile unsigned int revs; #endif void setup() { Serial.begin(115200); Serial.println("FAN CONTROL"); // prescaller for 31.372KHz // TCCR2B &= B11111000; // TCCR2B |= (0 << CS22) | (0 << CS21) | (1 << CS20); digitalWrite(PWM_PIN, LOW); pinMode(PWM_PIN, OUTPUT); #if FAN_WIRES == 4 attachInterrupt(digitalPinToInterrupt(SENSOR_PIN), interruptHandler, FALLING); #endif } void loop() { int pwm, pwmGpio; for (pwm = 0 ; pwm <= 100 ; pwm += 10) { Serial.print(pwm); Serial.print("%: ("); pwmGpio = pwm * 2.5; Serial.print(pwmGpio); Serial.print(") "); analogWrite(PWM_PIN, pwmGpio); delay(2000); #if FAN_WIRES == 4 Serial.print(" speed = "); Serial.println(getSpeed()); #else Serial.println(); #endif } for (pwm = 90 ; pwm >= 0 ; pwm -= 10) { Serial.print(pwm); Serial.print("%: ("); pwmGpio = pwm * 2.5; Serial.print(pwmGpio); Serial.print(") "); analogWrite(PWM_PIN, pwmGpio); delay(2000); #if FAN_WIRES == 4 Serial.print(" speed = "); Serial.println(getSpeed()); #else Serial.println(); #endif } } #if FAN_WIRES == 4 unsigned int getSpeed() { static unsigned long lastMillis; static unsigned int lastRead; unsigned long elapsed = millis() - lastMillis; if (elapsed > 1000) { detachInterrupt(digitalPinToInterrupt(SENSOR_PIN)); double correctionFactor = 1000.0 / elapsed; lastRead = correctionFactor * revs / 2 * 60; revs = 0; lastMillis = millis(); attachInterrupt(digitalPinToInterrupt(SENSOR_PIN), interruptHandler, FALLING); return lastRead; } } void interruptHandler(void) { revs++; } #endif