// Pin setup const int pwmPin = 9; // PWM output to transistor base const int tachPin = 2; // Tach input from fan const int buttonPin = 7; // Pin of the button volatile unsigned long tachCount = 0; unsigned long lastTachCount = 0; unsigned long lastMillis = 0; int rpm = 0; int speed_percent = 0; int speed = 255 - (speed_percent * 2.55); // Valore di default // Interrupt routine for tachometer void tachISR() { tachCount++; } void setup() { pinMode(pwmPin, OUTPUT); pinMode(tachPin, INPUT_PULLUP); pinMode(buttonPin, INPUT_PULLUP); attachInterrupt(digitalPinToInterrupt(tachPin), tachISR, FALLING); Serial.begin(9600); } bool lastButtonState = HIGH; unsigned long lastDebounceTime = 0; const unsigned long debounceDelay = 200; // ms void loop() { // // Imposta la velocità da seriale se disponibile // if (Serial.available() > 0) { // speed_percent = Serial.parseInt(); // if (speed_percent >= 0 && speed_percent <= 100) { // speed = map(speed_percent, 0, 100, 255, 0); // Converti percentuale in valore PWM (0-255) // Serial.print("Nuova velocità impostata: "); // Serial.print(speed_percent); // Serial.println("%"); // } // } // Imposta la velocità se il pulsante è premuto bool buttonState = digitalRead(buttonPin); if (buttonState == LOW && lastButtonState == HIGH && (millis() - lastDebounceTime) > debounceDelay) { speed_percent = speed_percent + 10; if (speed_percent > 105) { speed_percent = 0; } speed = map(speed_percent, 0, 100, 255, 0); lastDebounceTime = millis(); } lastButtonState = buttonState; analogWrite(pwmPin, speed); // Calcola RPM ogni secondo if (millis() - lastMillis >= 1000) { // La ventola 4 pin di solito genera 2 impulsi per giro rpm = (tachCount - lastTachCount) * 30; // 2 impulsi/giro, 60 sec/min lastTachCount = tachCount; lastMillis = millis(); Serial.print("Velocità impostata: "); Serial.print(speed_percent); Serial.print("% | RPM letti: "); Serial.println(rpm); } }