Refactor speed handling logic for improved validation and readability

This commit is contained in:
2025-10-03 17:04:46 +02:00
parent 1b208601d4
commit d7bcdf191c

View File

@@ -6,8 +6,11 @@ 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 = 0;
int speed_percent = 30;
int speed = 255 - (speed_percent * 2.55); // Valore di default
// Interrupt routine for tachometer
@@ -23,20 +26,26 @@ void setup() {
Serial.begin(9600);
}
bool lastButtonState = HIGH;
unsigned long lastDebounceTime = 0;
const unsigned long debounceDelay = 200; // ms
// Handle new speed
void newSpeed() {
}
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("%");
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
@@ -47,8 +56,8 @@ void loop() {
if (speed_percent > 105) {
speed_percent = 0;
}
speed = map(speed_percent, 0, 100, 255, 0);
lastDebounceTime = millis();
speed = map(speed_percent, 0, 100, 255, 0); // Converti percentuale in valore PWM (0-255)
}
lastButtonState = buttonState;
@@ -61,9 +70,13 @@ void loop() {
lastTachCount = tachCount;
lastMillis = millis();
Serial.print("Velocità impostata: ");
Serial.print(speed_percent);
Serial.print("% | RPM letti: ");
Serial.println(rpm);
if (speed_percent < 10) {
Serial.println("OFF");
} else {
Serial.print("Velocità impostata: ");
Serial.print(speed_percent);
Serial.print("% | RPM letti: ");
Serial.println(rpm);
}
}
}