Arduino PID library & segway

I posted this a couple of days back in Programming Questions and it didn't get any response, but I realized it might be better suited to this forum. I hope I'm not breaking any rules by reposting it here (I couldn't find a way to move it).

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!

Are you trying to control angle?

The setpoint is angle = 0 degrees (vertical), which is achieved by controlling the motor speed.

Thanks

Essentially I filter the gyroscope and accelerometer together to get an angle which seems to be fairly accurate

Fairly accurate? What does that mean?

If the device is clamped at zero degrees, the measured angle is stable / fluctuation / off by A degrees / what?