/*
Soft Starter Code
https://forum.arduino.cc/t/soft-starter-code/1292579/7
2024-08-18 by noiasca
*/
// a generic class for motors with soft start/soft end
class Motor {
const uint8_t pin; // a PWM GPIO to be used as output
uint32_t previousMillis = 0; // for time management according to the example "Blink Without Delay"
uint8_t speed = 0; // the current speed of the motor
public:
Motor (const uint8_t pin) : pin(pin) {}
void accelerate(uint32_t currentMillis = millis()) {
if (speed < 255 && previousMillis - currentMillis > 12) {
previousMillis = currentMillis;
speed++;
analogWrite(pin, speed);
Serial.println(speed); // debug only
}
}
void decelerate(uint32_t currentMillis = millis()) {
if (speed > 0 && previousMillis - currentMillis > 6) {
previousMillis = currentMillis;
speed--;
analogWrite(pin, speed);
Serial.println(speed); // debug only
}
}
void stop() {
if (speed > 0) {
speed = 0;
analogWrite(pin, speed);
}
}
};
//create an instance of a motor and assign the pin
Motor motor(6); // PWM pins UNO (R3 and earlier), Nano, Mini 3, 5, 6, 9, 10, 11
const uint8_t pedal = 5; // the pedalswitch connects to VCC, needs an external pulldown
void setup() {
Serial.begin(115200);
}
void loop() {
if (digitalRead (pedal) == HIGH) {
motor.accelerate();
}
else {
motor.decelerate(); // or motor.stop() without any deceleration
}
}
//