Tuning PD loop turn with Inertial Sensor

This is some code for a PD turn that uses the inertial sensor. I was wondering how I would tune kP and kD so that it would work best for our robot. Also, if anyone knows how use voltage instead of velocity, I would appreciate help with that.

void pdTurn(double degrees) //PD loop turn code (better than the smartdrive and P loop methods once kP and kD are tuned properly)
    int dt = 20;  // Recommended wait time in milliseconds
    double target = degrees; // In revolutions
    double error = target - Inertial.rotation();
    double kP = .7;
    double kD = .1;
    double prevError = error;
    while (std::abs(error) > 1) // Allows +- 1 degree variance, don't reduce unless you know what you are doing
      error = target - Inertial.rotation();
      double derivative = (error - prevError)/dt;
      double percent = kP * error + kD * derivative;
      leftGroup.spin(directionType::fwd, percent, pct);
      rightGroup.spin(directionType::rev, percent, pct);
      prevError = error;
    Brain.Screen.print("Inertial Sensor Not Detected");

How to use volts: change it to voltageUnits::volt or volt where you said pct

to tune it:

Set everything to 0

turn kP up until the robot oscillates a little bit around the desired point

turn kD up until it stops oscillating.

I also recommend using a kI eventually, it’s very helpful for turns.

1 Like

How would I get a starting value for kD and kP and know how much to increment them by? I understand the theory but I dont know how to apply to real values.

You can think of them as conversion values: converting error (in degrees of orientation) to rpm for motors or voltage for motors. You will probably get a lot of people who will say

It depends.

If you’re controlling rpm with your PID, maybe start at the ones place for kP. Sorry I don’t know more. The best you can do is guess, “So I have an error of 90. Do I really want to multiply this by 100 and pass that to the motors for rpm? Probably not. How about 2? Sounds closer.” Then continue upping and downing it at the ones place, the 0.1 place, the 0.01 place, and as you get closer, change it more and more slowly. Beware with kI, though, I hear. It adds up quickly.

1 Like

I’m having issues with this code. Sometimes it’ll turn, and then wait a bit (2 seconds ish) then adjust, and then finish its turn. Kind of like a delay then autocorrection. Does anyone know anything about this

I experienced that a little bit when I was trying to make a PID and turned kD up too far. Do you thoroughly understand how PID works? And also, we need to see your code.

1 Like

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