# Gyro PID

Does anyone have a PID for the drive train using gyro?

Yes, essentially itâ€™s the same like using encoders but depending on how the gyro is tuned; youâ€™ll have to tune your constants differently, hereâ€™s something.

``````
int lastError;
double kP, kI, kD (set these of course; but you will need to tune them)
int current = gyroValue
int error = error - current;

//calculate integral
int integral += error;

//calculate derivative
int derivative = lastError - error;
lastError = error;

//all together
motorSet(error*kP + integral*kI + derivative*kD);

``````

Itâ€™s really the same as using encoders or any other sensor, just recognizing the scaling of it; and use the motorSet for some to be positive and others to be negative so that the robot actually turns.

1 Like

Scroll down to the â€śResourcesâ€ť section of this article for some links & info on gyro PID:

This other article has lots of other gyro information:

If you like dealing in encoder clicks, you can just use one of the available encoder-based PID controllers. (This one by @jpearman, for instance: https://vexforum.com/t/a-pid-controller-in-robotc/20105/1 )

Drive one side of the chassis as the master, calculate the PID error on the other side. Use the gyro rotation angle by turning it into a lag or lead on the slave side.

The lag or lead distance of the slave side is:

2 * wB * sin (.5 theta)

where:

• wB is the wheel base, or the measure from the center of the left side wheels to the center of the right side wheels, and
• theta is the angle measured by the gyro

To work in quad encoder clicks, you can convert this distance into clicks by noting that inches per click can be calculated with:

(Diameter in inches *Pi)/360 clicks

As a quick calculation, assuming exact 4 inch diameter wheels, I calculate that there are .035 inches/click. Using the first equation above and assuming 15 inches between centerline of the two wheel sides, I calculate there are 2 * 15 inches * sin(.5 deg), or .26 inches of lag or lead per degree of turn.

So, (.26 clicks/deg) /(.035 in/click) gives 7.4 clicks/degree

Since the gyro can measure and report tenths of degrees, this means the smallest lag or lead you can work with is .74 clicks/tenth degree.

So you can read the gyro, decide based on the sign (positive or negative) of the turn angle whether youâ€™re dealing with a lag (slow slave side) or lead (fast slave side) and convert the angle into a number of quad encoder clicks to use as your PID error.