# Rotation with gyroscope (and maybe accelerometer?)

We are looking for a way to rotate a robot within about +/- 5 degrees of accuracy. We are using this three-axis gyroscope currently. Does anyone have any sample code or help on doing this? Would it be beneficial to pair an accelerometer with the gyro for this? (We have an accelerometer also.)

Right now, we’re just turning using encoders on the wheels, and we are using a calculation based on the degrees vs ticks of the encoders. This works decently; however, in environments with different (or slanted) surfaced, the turns are very inaccurate.

Advice or other help would be much appreciated, even if it is something other than using a gyro/accelerometer.

Edit: We are not looking for any orientation data. We simply want to rotate the robot 90 degrees, or however many degrees we pass to it via a turn function. For the turn, we are just powering one side with a positive speed and the other with a negative speed to make a point turn.

Thanks.

Do you want to "rotate" a robot by some amount, determined to a certain level of accuracy, or know its final orientation (with respect to some direction like North) to that accuracy?

The rate gyro won't tell you what direction the robot is facing, only how fast it is rotating at any given time. You can get an estimate of the direction by integrating over time (every small interval of time: measure the current rate and, assuming the average of the previous and current rate applied to the latest time interval, multiply the average rate by the interval and add to the previous angle to get a new angle). This is subject to accumulating error.

To get more orientation data you can use a magnetometer/compass. It will give you orientation relative to the local magnetic field. That works until a magnetic object causes a shift in the local field.

Without some kind of external reference there is no good way to know orientation in space. I have heard about robots that use IR spots projected on the ceiling to determine position and orientation in an enclosed space. This takes more computing power than you can expect from an Arduino UNO or MEGA.

We are not looking for any orientation data. We simply want to rotate the robot 90 degrees, or however many degrees we pass to it via a turn function. For the turn, we are just powering one side with a positive speed and the other with a negative speed to make a point turn.

Also, sample code is greatly appreciated.

The total angle rotated about any axis is obtained by integrating the gyro rate data for that axis with respect to time. However, gyros are noisy, temperature sensitive and drift, so the accuracy of the result will depend strongly on your circumstances.

In outline, your loop might look something like this:

angle = 0;

loop {