For driving straight, you don’t actually need to integrate the gyro output. While that method results in more intuitive controls code, you can re-arrange your controller to accept the non-integrated gyro rate.
Consider the following pseudo-code:
Left_Motor[n] = Left_Motor[n-1] + Gain*(heading[n] - desired_heading)
Right_Motor[n] = Right_Motor[n-1] - Gain*(heading[n] - desired_heading)
Where “n” is a time index.
This is essentially two proportional velocity controllers with the gyro angle (integration of the rate) as the process variable.
We can differentiate (in a discrete sense) both sides of these equations!
Left_Motor[n] becomes (Left_Motor[n] - Left_Motor[n-1]).
Left_Motor[n-1] becomes (Left_Motor[n-1] - Left_Motor[n-2]).
heading[n] becomes rate[n], and desired_heading (a constant) becomes desired_rate (which is zero).
Repeat for the right side.
So now,
Left_Motor[n] - Left_Motor[n-1] = Left_Motor[n-1] - Left_Motor[n-2] + Gain*rate[n]
You can do some algebra and re-arrange to get:
Left_Motor[n] = 2*Left_Motor[n-1] - Left_Motor[n-2] + Gain*rate[n]
Look weird? Absolutely. But will it work correctly? Yes.
You do probably will want to filter the rate[n] input since Kevin’s oversampling and heading calculation essentially accomplishes this for you (integration can be considered a low-pass filter).
I haven’t tried this method myself, as Kevin’s code saves us a lot of time and works great, but if you really want to DIY, this will let you cut out the hardware ADC.
General Note: This method of differentiating both sides of a controls difference equation is a powerful tool, and is a good way to derive control equations that you hadn’t thought of before! Just beware that integration is usually a GOOD thing in control systems and you usually don’t want to remove it without a compelling reason. But if you, for example, remember the position version of a PID equation, you can quickly generate the equivalent velocity control PID equation using this method.