Setting a variable equal to a value based on a function of time

Hello,

I am using my arduino to control a linear actuator (motor). Right now, it entends at speed 255 (full speed, based on a range from 0 - 255), it pauses, then it retracts at speed 255. The code to do the retraction is simply setting the speed to 255 on the "Raise" PWM pin and waiting a second while it comes up, before any more code is executed. This is what I have:

  analogWrite(LPWM, 0);
  analogWrite(RPWM, 255);
  delay(1000); // 1 Seconds
  putstring_nl("Up");

What I'd like to do is decrease the speed as the time increases. So, replacing the second line in the above snippet with something like:

analogWrite(RPWM, speed = sqrt((1000 - time)/1000) * 255)

...where "time" goes from 0 seconds (the start of that delay in my code above) to 1000 milliseconds. This would decrease the speed non-linearly, slowing it down more as we get closer to the end of the second. I'm not sure how to "start a timer" if you will, to allow this function to work properly. Anyone know how I can implement this idea?

Thank you!

Quit using the delay(...) function and learn to use the millis() function. If you need it, there is a great tutorial near the top of this forum.
The millis() function will tell you the time (as an unsigned long) that you started, and the difference between millis() and the time that you started will tell you how much time has passed. If the difference is greater than 1000 then more than one second (1000 milliseconds) has passed.

When it comes to using millis(), all variables involved with time calculations should be declared unsigned long and the calculations should be subtraction, NEVER addition.

You also need to learn the difference between integer calculations and floating point calculations.

For example,
1/2 is zero, but
1/2.0 is 0.5

Thank you for pointing me in the right direction.

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