Problem with balancing robot

Hello all,

My current project is a balancing robot, it is my first "major" arduino project. I have the arduino read acceleration from a 3 axis accelerometer, and rate of rotation from a gyroscope, combine these two in the software on the arduino and come up with a current angle for the robot. Both sensors are analog output. The arduino then drives two geared dc motors attached to the wheels through an l298 h-bridge.

The trouble I am having is this: when the power supply to the motors is off, the arduino comes up with the correct angle for the robot. When the arduino is allowed the drive the motors without speed control (just using digitalWrite) it also comes up with the correct angle. When I start using pwm to vary the speed of the motors though, the angle is not even close.

I am looking for suggestions to eliminate this noise. I have decoupling capacitors on every element of the robot and am even using a separate battery to supply the Vss power to the motors through the l298. Is there a problem using analogRead while a pwm output is happening on another pin?

When I start using pwm to vary the speed of the motors though, the angle is not even close.

That's not obvious from the code you posted. Oh wait...

Is there a problem using analogRead while a pwm output is happening on another pin?

Normally, no. What are you reading from an analog pin, though?