Motor direction and ramping changes. Interupts?

I have a system running which controls a couple of motors. I can set speed and direction with no problem and, of course, I can stop/start or change the speed or direction at any time.

I can also ramp speed up or down at a given rate within a loop. However with a simple loop, there's nothing I can do to change the motor speed or direction (or stop it) while the simple loop ( for loop or while loop) is executing.

What would be the general principle (using an Arduino MEGA) behind having ramping functions which could run independently while the overall program was doing something else (looking at key presses, reading sensors etc.) and having the loop interupted if an event took place which required a change in speed or rotational direction of the motors?

Hello
Well my recommandation is the usage of an event driven FSM.
73

What kind of motors ?

Don't use for-loops or while-loops. Let loop() do the work. Let's say that your loop() looks like below

void loop()
{
  for(uint16_t cnt=0;cnt<255;cnt++)
  {
    analogWrite(yourPin, cnt);
    delay(100);
  }
}

Take the body of the for-loop and place it in a function; I called it ramp(). It will return a bool to indicate when one ramp was completed. Add a static variable to keep track of count.

bool ramp()
{
  static uint16_t cnt;
  
  if(cnt>255)
  {
    cnt=0;
    return true;
  }

  analogWrite(yourPin, cnt++);
  delay(100);
  
  return false;
}

And call it from loop().

void loop()
{
  bool done = ramp();
  if(done == true)
  {
    Serial.println("Ramp complete");
  }
  // other stuff here
}

Not tested, not compiled. Just to give you the idea.

Next you have to replace delay() by a milis() based approach to get it really responsive.

Hi,

Can you please post the code you are talking about?

Thanks.. Tom.. :grinning: :+1: :coffee: :australia:

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