Map()ing PWM to Millis(() is that possible?

Hello, I am trying to start/stop a dc motor in a smooth way, and I remember I read and bookmarked a site where they had a code snippet to use map() and millis(() over a value of PWM to soft stop a motor in a given period of time. But I cannot find it anymore in my bookmark's list ! So I tried to make an basic seudocode like:

pwmVal=map( pwmVal, startingMillis,finishingMillis,givenPWM,255)

while keeping track of the millis() passed. My dc motor stop with 255 pwm value and keeps running with lower values.

let say I want the motor goes from running to full stop in 5 seconds.

So do you think guys is this feasible ? I don't have any code yet,just the general idea but not sure if this is the right way to do it.
Thanks in advance!

If the PWM output needs to change from 255 to 0 over a period of 5 seconds then you need to decrease the value written to the PWM output by 1 about every 20 milliseconds (5000/255)

Using the BlinkWithoutDelay timing method with a period of 20 milliseconds, when each period ends reduce the PWM output by 1 until it reaches zero

1 Like

pseudo code

start = millis();
end = start + 5000;
loop
{
analogWrite(map(millis(), start, end, 0, 255));
}

1 Like

Actually the output must go from a working pwm value (motor is running) to 255 (motor stopped) cos my driver has inverted logic, so I get the idea, it just that map()/millis() solution looked so simple to implement ina couple of lines, sadly i cannot figure out how it was done . So doing my own math and timing is the way to go right?

yes, something like that! I know map loose some precision in the process but is not that a big deal in my case, just need a smooth stop. so I will try both solutions this nite and see how things go! will be back! thank you!

  unsigned long startFade = millis();
  const unsigned long fadeDuration = 5000;
  while (millis() - startFade < fadeDuration)
  {
    int pwm = map(millis() - startFade, 0, fadeDuration, startPWM, endPWM);
    analogWrite(MotorPin, pwm);
  }
1 Like

Done! For simplicity I made startFade = 0; and replaced while for if,so now I'm ready to stop the motor when it is needed, I thought I understood well the map() function but I was wrong, interesting enough, I see that the implicit variable to map (millis()-startFade) in this case, is not always the output variable that I will use to set the pin to pwm the motor as I did in my first post: pwmVal=map( pwmVal, startingMillis,finishingMillis,givenPWM,255)

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.