Arduino PID library & segway

Hey all,

I'm attempting to build a full size Segway replica with an Arduino Mega as the main controller, but I'm running into an issue using the PID library for the main control loop. Essentially I filter the gyroscope and accelerometer together to get an angle which seems to be fairly accurate, and then pass that to the PID controller to ask it for motor speed values. I can get the controller to function reasonably well when I carefully tune KP and KI, to the extent that it is possible to ride with some degree of control. However I hit a problem as soon as I add any KD value at all. At extreme angles KD seems to behave as it should and helps damp the movement back towards the upright, however at angles around 0 degrees the Differential value creates a huge amount of oscillation/vibration (to the point where it is damaging the physical structure). I don't understand how this is happening because it will occur no matter how small the KD value is (down to ridiculous values like 0.000000005 when KP = 50). The only way to prevent it is to set KD=0, but then of course I don't get any damping.

I've tried things like smoothing the differential output by passing it through a moving average and so forth but none of it seems to help. Does anyone have any ideas?

Thanks!