# Slow decrease in pwm to certain value

Just got my Arduino Uno, absolutely love it!

Im new to coding, but believe I am getting the hang of the basics so far.

Here is my question:

I'm running a motor via PWM and controlling the speed from a pot, 0-5v.

I am keeping the motor at a constant speed from 0-1v and then from 1-5v the motor increases its speed.

What I want to accomplish, is when the voltage drops from the pot below 1v, the motor SLOWLY decreases in speed back to the constant speed value, not at the same speed as the pot as turned.

Here is the code I have so far

``````int pot = A3;
int motor = 9;
int val = 0;

void setup()
{
Serial.begin(9600);
}
void loop()
{
float volt = val * (5.0 / 1023.0);

if (volt < 1) {
analogWrite(motor, 30);
}
else {
val = 255 * (volt/5);
analogWrite(motor, val);
Serial.println(val);
}
}
``````

``````  float volt = val * (5.0 / 1023.0);

if (volt < 1)
``````

These chips don't have FPUs, so floating point math should be used sparingly. This is an example of where it can be eliminated by a simple calculation:

``````1023 val / 5 volt = x val / 1 volt = 204.6
``````

So you can replace the if statement:

``````if (val < 205)
``````

Will do thanks for the advice!

``````else {
val = 255 * (volt/5);
if (currentVal < val)           // Don't forget to declare currentVal
{
analogWrite(motor, currentVal);
Serial.println(currentVal);
currentVal++;
delay (25);                 // Pick a delay that suits you, or take a look at "Blink without delay" example for more advanced method
}
}
``````

You'll also have to set currentVal to something smaller (I suppose 30) so it functions in the next iteration.
This place looks like a good place to do it:

``````if (volt < 1) {
analogWrite(motor, 30);
}
``````

If you want the motor speed to vary based on time, rather than following the pot value exactly, I suggest you separate out the motor speed implied by the pot position, and the speed that you have actually set the motor to. Allow the pot to adjust the 'demanded motor speed' instantly. Ten follow this with some code that compares the demanded motor speed with the actual motor speed and adjusts the actual motor speed. In this case you would probably want to design that code so that the actual speed was updated to the demanded speed immediately in the region where you want the motor speed to follow the pot exactly; where you want the motor speed to settle slowly you would alter the actual motor speed in small steps towards the demanded speed, using the technique demonstrated in 'blink without delay' to apply those small steps at regular intervals.

Although the description is pretty long winded, once you have got your head around the concept of writing non-blocking code and using millis() to carry out activities at timed intervals the code itself is pretty simple - the whole thing would probably only need half a dozen lines of code.