82 lines
2.3 KiB
C++
82 lines
2.3 KiB
C++
// 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;
|
|
bool lastButtonState = HIGH;
|
|
unsigned long lastDebounceTime = 0;
|
|
const unsigned long debounceDelay = 200; // ms
|
|
int rpm = 0;
|
|
int speed_percent = 30;
|
|
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);
|
|
}
|
|
|
|
// Handle new speed
|
|
void newSpeed() {
|
|
|
|
|
|
}
|
|
|
|
void loop() {
|
|
// Imposta la velocità da seriale se disponibile
|
|
if (Serial.available() > 0) {
|
|
int speed_read = Serial.parseInt();
|
|
if (speed_read >= 0 && speed_read < 10) {
|
|
Serial.println("Warning: Velocità minima perché la ventola giri è 10");
|
|
speed_percent = 0;
|
|
}
|
|
else if (speed_read >= 10 && speed_read <= 100) {
|
|
speed_percent = speed_read;
|
|
} else {
|
|
Serial.println("Error: la velocità deve avere un valore compreso tra 0 e 100");
|
|
}
|
|
speed = map(speed_percent, 0, 100, 255, 0); // Converti percentuale in valore PWM (0-255)
|
|
}
|
|
|
|
// 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;
|
|
}
|
|
lastDebounceTime = millis();
|
|
speed = map(speed_percent, 0, 100, 255, 0); // Converti percentuale in valore PWM (0-255)
|
|
}
|
|
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();
|
|
|
|
if (speed_percent < 10) {
|
|
Serial.println("OFF");
|
|
} else {
|
|
Serial.print("Velocità impostata: ");
|
|
Serial.print(speed_percent);
|
|
Serial.print("% | RPM letti: ");
|
|
Serial.println(rpm);
|
|
}
|
|
}
|
|
} |