Software > Software

Servo Code

<< < (2/2)

Mastermime:
Using PWM?

newInRobotics:

--- Quote from: Mastermime on December 01, 2012, 05:18:48 PM ---Using PWM?

--- End quote ---
To run servo You use PWM anyway. By run servo in segments I meant that if, say, servo turns 60 in 2s, then if You make it turn twice by 30 it will run slower as internal circuitry in servo makes servo axle rotate slower due to the fact that it has to travel shorter distance. Does it make sense?

jwatte:
The basic control loop you want to set up is a loop that runs over and over, and each time calculates:
Where am I now? (You have to remember this!)
Where do I next want to be?
When do I next want to be there?
Given that, what is the next small step I can take?

If you run this, say, 30 times a second (for a regular 30 Hz servo update cycle,) then it might look something like:


--- Code: ---int curTimeDelay = 1500; // center
int targetTimeDelay = 1500; // center
long millisToTarget = 0; // not changing
unsigned int lastTime = 0;

void setup() {
    lastTime = millis();
}

void loop() {

  readCommand(); // figures out possible new value of "targetTimeDelay" and "millisToTarget"

  while (millis() - lastTime < 30) {
    // do nothing
  }
  lastTime = millis();

  if (millisToTarget == 0) {
    curTimeDelay = targetTimeDelay;
  }
  else {
    long millisToGo = (targetTimeDelay - curTimeDelay);
    int deltaMillis = millisToGo * 30 / millisToTarget;
    curTimeDelay += deltaMillis;
    if (millisToTarget < 30) {
      millisToTarget -= 30;
    }
    else {
      millisToTarget -= 30;
    }

    setServoPWMTime(THE_SERVO, curTimeDelay);
}

--- End code ---

This code will move the target time given to the servo over a period of time, rather than just telling it "I want you there NOW!"

Navigation

[0] Message Index

[*] Previous page

Go to full version