const int pwmPin = 9; // PWM pin to control motor speed int currentSpeed = 0; // Initial motor speed (0 - 255) int targetSpeed = 0; // Target motor speed (0 - 255) int stepSize = 5; // Increment value for smooth transitions (adjust this value as needed) unsigned long previousMillis = 0; // To track time for smooth transitions const long interval = 20; // Interval time for speed updates (in milliseconds) void setup() { pinMode(pwmPin, OUTPUT); Serial.begin(9600); // Start Serial communication at 9600 baud rate Serial.println("Motor Speed Control - Use keys: '1' to '5' to change speed"); } void loop() { // Check if there's any data from the serial monitor if (Serial.available() > 0) { char key = Serial.read(); // Read the incoming byte // Map keypresses to target speeds if (key == '1') { targetSpeed = 14; // Low speed } else if (key == '2') { targetSpeed = 102; // Medium low speed } else if (key == '3') { targetSpeed = 153; // Medium speed } else if (key == '4') { targetSpeed = 204; // Medium high speed } else if (key == '5') { targetSpeed = 255; // Full speed } else if (key == '0') { targetSpeed = 0; // Stop motor } // Print the selected target speed to the Serial Monitor for feedback Serial.print("Target Speed: "); Serial.println(targetSpeed); } // Gradually adjust the motor speed to the target speed for smooth transitions unsigned long currentMillis = millis(); // Only update the speed if enough time has passed if (currentMillis - previousMillis >= interval) { previousMillis = currentMillis; // Gradually increase or decrease the speed to reach the target if (currentSpeed < targetSpeed) { currentSpeed += stepSize; // Increase speed if (currentSpeed > targetSpeed) { currentSpeed = targetSpeed; // Don't overshoot the target } } else if (currentSpeed > targetSpeed) { currentSpeed -= stepSize; // Decrease speed if (currentSpeed < targetSpeed) { currentSpeed = targetSpeed; // Don't overshoot the target } } // Set the new motor speed (PWM signal) analogWrite(pwmPin, currentSpeed); } }