## [TUT] [HARD] Gyros and Accelerometers: The Basics

21 posts / 0 new
Author
Message

Gyros and Accelerometers: The Basics

1. Introduction

Once upon a time, gyros and accelerometers where mythical devices that started at the cost of a small car and ranged to the price of a villa in Monaco. Fortunately, the cost of these sensors dropped substantially in recent years where they are now well in the price range of a student of hobbyist.

Whilst gyros and accelerometers are cool, they are full of traps for the unwary. This tutorial starts covering the basics of gyros and accelerometers and goes through some of the common pitfalls. In later tutorials, we'll go into more advanced topics like how to do your own Pitch and Roll calculations.

Before getting too far into it, it's worth looking at http://en.wikipedia.org/wiki/Yaw... to see my definitions for "pitch, roll and yaw"

-----------------------------------------------------------
2. What's a Gyro?

Put simply, a gyroscope (or gyro for short) is a device that measures angular rate about a particular axis - that is, the rate of change of angle with time.

When I talk about "rotation about a particular axis", there is a convention associated with it. It's the same as for a magnetic field - stick your right-hand thumb in the direction of the axis and curl your fingers around. The direction of your curled fingers is the positive direction of rotation.

Not all devices will measure rate about the same axis. For example, so called "yaw-rate" gyros will measure about the axis perpendicular to the circuit board on which it's mounted. Other devices measure about the "x-axis" which is usually in the lengthways direction of the chip.

The reason why "yaw-rate" is in inverted commas is because it's only truly "yaw-rate" when the circuit board is precisely level with the ground. Imagine standing the board directly on it's side with the axis pointing to the right - it will now measure the rotation rate of doing a backflip, not a flat spin as would be case when it's level with the ground.

As a result, a gyro will always read the rotation in the body-fixed co-ordinate frame. That is, unless it's perfectly aligned with an axis, it will read a combination of pitch-rate, roll-rate, and yaw-rate. Change the axis a little and it reads a different proportion of the various rates.

Of course, this is an ideal case - Like all sensors, they have errors and are not as easy to deal with as what might be imagined. I'll go through these a little later since many of the errors are very similar to accelerometer errors.

-----------------------------------------------------------
3. What's an accelerometer?

An accelerometer reads linear acceleration. Unlike gyros which (with notable exceptions) read only about a single axis, most commercial low-cost accelerometers have three accelerometers built into one package - that is, they can sense accelerations in the x-, y- and z-directions.

Unless you're in orbit or in perfect free-fall, accelerometers will always read gravity as well. Whilst this seems like a curse, in reality it's quite useful - it means we have a vertical reference.

Like gyros, accelerometers will always output accelerations in the body-fixed coordinate frame - a small tilt will mean that x- and y- will also read some portion of gravity along with the z-axis. Hence, by measuring the proportion of gravity in the x-direction (or y-direction) compared to the z-direction, we can work out our pitch (or roll) angle to within the accuracy of the sensor! Unfortunantly, if you're not perfectly still, your estimate of your angle will be affected by small changes in motion.

In addition to sensing angle and motion, accelerometers are sometimes used to measure and analyse vibration - it can be useful for determining when equipment needs to be serviced.

-----------------------------------------------------------
4. Interfacing to Gyros and Accelerometers

The interface to a gyro or accelerometer is entirely dependent on the device itself. Traditionally, they've been analogue out (and are still oftne cheaper in many instances), but more modern devices are I2C, SPI or PWM.

If you're using an analogue to digital converter, be aware on how they can introduce errors into your system - temperature, bias and scale factor are key to getting a good inertial sensor system.

Any mega AVR is more than capable of taking measurements from multiple sensors (including if there is an ADC involved) and performing some basic processing. Some are even capable of doing a full attitude solution calculation on the AVR itself at something like 50-100Hz.

For anything more complicated, it's worth using an AVR for sampling the sensors then sending the data off to a more powerful processor for sophisticated algorithms (there's whole textbooks written on algorithms alone).

-----------------------------------------------------------
5. What errors exist on Gyros and Accelerometers?

The first thing you'll notice when you plug in your first accelerometer is that they're really noisy. Seriously noisy! Unfortunately, unless you're willing to spend thousands of dollars, you'll have to do a lot of filtering to make these sensors clean.

So what do I mean by clean?

My original training is in aerospace, but I'm firmly ground-based these days and I dabble in these types of sensors as part of my job from time to time. As such, I tend to view these sensors through three main classes of applications:
* Motion detection (e.g. hard disk falling, pedometer)
* Attitude measurement (e.g. flight control, chassis stability, robotic arms)
* Inertial Navigation (e.g. airliners, military jets)

Each one requires a full order of magnitude (or more) better performance out of the sensor with a multiple order of magnitude cost difference.

Motion detection tends to be the simplest: A high pass filter, integrator and threshold on a cheap accelerometer tends to be sufficient - many chips even have such algorithms built in. Noisy devices in this class are very common, because all they're really doing is looking for deviations from a steady-state value of the sensor.

Attitude measurement relies on the accelerometer detecting the gravity vector - simple trigonometry can resolve the measurements into pitch and roll angles. Any noise or bias on the measurements directly corresponds to noisy attitude estimates, with a rule of thumb of about 1 milliradian of angular error per milli-g of error (noise/bias).

Inertial Navigation is by far the most demanding on these sensors - the purpose is that you're trying to integrate acceleration **twice** to get an estimate of position. Therefore, any bias will quadratically increase error with time, and any noise will turn into a doubly integrated random walk. Given a flight can easily last 8 hours or more, you can see why they demand precision!

So can't I just filter it for a long time to clean up the signal?

Well, Yes and No, depending on your application. If you're a non-static application, then quite clearly you can't average for seconds at a time!

Even if you've got a static application, it's not just a matter of averaging/low pass filtering forever. The reason being that there's not just white noise acting on the device.

In addition to white noise, there are several other types of noises not always seen or cared about in the electronics world. I'll limit myself to a couple of these, which tend to dominate low-cost devices:
* Turn-on bias
* Temperature bias
* Bias Instability ("Flicker Noise", "Correlated Noise", "Gyro drift")
* Bias Random Walk
* Scale Factor error.

In general, you'll only need to start worrying about these errors when doing something needing precision, like attitude measurement.

Turn-on bias is a constant offset that changes every time that the device is turned on - not too much different from having to zero a pair of digital scales.

Temperature bias is a change in the bias of these devices as a function of temperature. After all, MEMS sensors are just little machines in silicon and temperature will expand/contract the structures inside the device. This is particularly dominant - especially if your device is exposed outdoors.

Bias instability, sometimes called gyro drift (it has a specific meaning, but I'll talk generally) refers to random changes in the bias of these devices just because they feel like it, or because they're having a bad day. It happens very slowly and like white noise, you can't predict it (although you can statistically characterise it)

Random Walk Bias also refers to random fluctuations to the bias, but one that follows a "random walk process". See http://en.wikipedia.org/wiki/Ran...

The result is, after averaging for a period of time, the standard deviation of your average actually increases because of the slow fluctuations in bias listed. We generally use a tool known as an Allan Variance chart to analyse the bias performance of these sensors.

I've used the word "bias" a lot. It's pretty much as you'd expect - a constant (or slowly moving) offset from the true measurement. Because it moves very slowly, it's actually quite difficult to deal with - you just can't average it away like you can with white noise!

Unfortunately, because none of the low-cost datasheet publishes any of the standard errors (there's an IEEE standard), there's generally a lot of playing around before working out if a device is suitable for your application.

-----------------------------------------------------------
6. FAQs

a) So what are "Degrees of Freedom" (DoF)?

This refers to the number of independent dimensions that an Inertial Measurement Unit (IMU) is capable of measuring. There are three linear dimensions (e.g. acceleration) and three angular dimensions (e.g. angular rate - gyros). Hence, 6DoF.

For a "fully observable" IMU, you need to be able to measure all 6 degrees of freedom. Otherwise, you'll need to "guess" the other motion parameters.

Some units of "9DoF" or "8-axis". Usually, this refers to an IMU that also contains a 2-axis or 3-axis magnetometer. It's marketing talk, not true "degrees of freedom" as such, but the compass *is* useful (so long as you know there's no metal nearby!)

---

b) I can use an IMU to measure position, right?

In theory, you can integrate the accelerometers twice to get position (adjusting for the attitude by integrating the gyros) to make what's called an Inertial Navigation System (INS).

Unfortunately, as soon as you start integrating, you start accumulating errors - twice for the accelerometers and three times for the gyros, as the attitude couples into position! Therefore, for the grade of sensors you can get from SparkFun, inertial navigation so useful only for a few seconds at best.

In general, you need a good quality IMU to perform Inertial Navigation. For example, the Novatel SPAN is about \$40K, and will give (at best) 7m after one minute, though in my experience, even this is optimistic.

There are certain trick you can use to make it better, but without reference to an external source (e.g. GPS), the position and attitude will drift forever.

-----------------------------------------------------------
7. Legal Stuff

(c) 2010, damien_d, https://www.avrfreaks.net

You may share this document under the Creative Commons Attribution-Share Alike 3.0 Unported Licence. You can read the full text of the licence at http://creativecommons.org/licen...

To the maximum possible extent under law, there is NO WARRANTY associated with this document. You should seek independent technical and legal advice before using this document as the basis of any design.

-----------------------------------------------------------

This was originally a post in the following thread:
* https://www.avrfreaks.net/index.p...

I'm intending to do a tutorial series on accelerometers and gyros. As I write them, I'll add the links here.

-----------------------------------------------------------
9. Improving this Tutorial

This tutorial is intended to be a living beast. If you can spot mistakes, provide constructive criticism or otherwise suggest improvements, just leave a post below.

-----------------------------------------------------------
10. Edit History

1.0 - 2nd Feb 2010, Initial version
1.1 - 4th Feb 2010, Small amendment for gyro drift
1.2 - 24th Sep 2010, Added FAQ
1.3 - 8th Feb 2011, Fixed typo

-- Damien

Last Edited: Mon. Feb 7, 2011 - 10:20 PM

It's worth to say that data from gyro and accel is often filtered by Kalman filter.

Kalman filter was first introduced in NASA Moon missions but is still widely used. Inputs of the filter are sampled data, on the output you get "smooth" data. It can even "guess" data when samples are not available - pure magic.
It does not require much processor power, so it can be implemented in C for AVR microcontrollers.

mogor wrote:
It's worth to say that data from gyro and accel is often filtered by Kalman filter.

Kalman filter was first introduced in NASA Moon missions but is still widely used. Inputs of the filter are sampled data, on the output you get "smooth" data. It can even "guess" data when samples are not available - pure magic.
It does not require much processor power, so it can be implemented in C for AVR microcontrollers.

See tutorial here:
* https://www.avrfreaks.net/index.p...

Without aiding sensors (e.g. GPS, odometers), there's little a KF can do that can't be done via a complementary filter.

Also, I'd hardly say it's magic; the accuracy of guessing your states when there are no measurements entirely depends on the quality of your process model (motion model). Even if they're modelled well, the uncertainty will grow forever with time.

For most practical applications, a KF cannot be used directly - it can only be used on "linear" systems. There are workarounds for non-linear systems, which attitude determination certainly is (for example, you can an Extended Kalman Filter), but they introduce their own problems.

It's true that it can be implemented on a AVR, but only for very small state vector sizes and only at limited sample rates - it relies on a matrix inverse which has computing time O(3) (i.e. scales with the cube of the size of the state vector).

-- Damien

You didn't mentioned about gyro drift (I found link in response to post about self-balanced robot). To eliminate that it's better for you to use Kalman filter and accel readings.
Of course "magic" of the filter lays in the math, it wasn't my intention to explain how it works.

mogor wrote:
You didn't mentioned about gyro drift (I found link in response to post about self-balanced robot).

It's part of "Bias Instability". I've now mentioned it explicitly.

-- Damien

I am planning to use an accelerometer to determine whether a fabrication machine is working or not. I'll probably be interested in 3 states - motor off, motor on, tool cuting the prefab.
I assumed that I can accomplish this task with cheaper accelerometers. Was I wrong?

Of course it all depends on the manufacturing process and parameters, but I am talking about processes for which the 3 states are pretty clearly differentiated by vibration amount (observed personally by touching the machine case).

Thanks

Stormofwar wrote:
I am planning to use an accelerometer to determine whether a fabrication machine is working or not. I'll probably be interested in 3 states - motor off, motor on, tool cuting the prefab.
I assumed that I can accomplish this task with cheaper accelerometers. Was I wrong?

Health monitoring using vibrations is commonly done in the aerospace industry ("HUMS"), and I have seen references to it being done for washing machines.

The trick is choosing one with enough bandwidth to get all the significant vibration harmonics in - many limit the bandwidth of the sensor to (for example) 30Hz to limit the amount of noise.

In this scenario, unlike navigation, very low frequencies (i.e. bias drift) is not of interest and therefore can be high pass filtered.

-- Damien

cool. Thank you Damien!

Hey damien,

I'm curious to know your thoughts on this thread: http://forum.sparkfun.com/viewto...

I ask because I'm trying to calculate the angle of rotation myself by integrating the gyroscope, and well, I've spent a lot of my time scratching my head.

The gyro has both a high pass filter and a low pass analog soldered RC filter.

Here is the gyro signal in time when rotating the gyro 90 degrees one way and then back. I repeated this action a few times:

And here is the integrated signal in the hope of obtaining angular position:

Now, I know I'm integrating correctly because on differentiating, I get back the original signal. What has me perplexed is that the angular position is drifting and the angle itself is somehow greater than 400 degrees! :(

I'm using the LPR5150AL by the way. Any help you could give or anybody else could provide would be great.

Thanks.

tabshizzle wrote:
Hey damien,

I'm curious to know your thoughts on this thread: http://forum.sparkfun.com/viewto...

I ask because I'm trying to calculate the angle of rotation myself by integrating the gyroscope, and well, I've spent a lot of my time scratching my head.

The gyro has both a high pass filter and a low pass analog soldered RC filter.

Here is the gyro signal in time when rotating the gyro 90 degrees one way and then back. I repeated this action a few times:

And here is the integrated signal in the hope of obtaining angular position:

Now, I know I'm integrating correctly because on differentiating, I get back the original signal. What has me perplexed is that the angular position is drifting and the angle itself is somehow greater than 400 degrees! :(

I'm using the LPR5150AL by the way. Any help you could give or anybody else could provide would be great.

Thanks.

A high pass filter is bad, bad news for most applications, but somewhat OK if all you're doing is motion detection.

The low pass filter is necessary to limit noise. It shouldn't be too low, however.

The shape integration looks about right, though there is a a scale factor that's missing somewhere. Depending on the cut-off frequency of the HPF, it may well remove slow and steady state motions (such as a constant turn), which will cause some of the problems that you see in the plot.
[/edit]

Try doing a slow turn (e.g. aircraft, or tractor) and the small-ish steady angular rate gets filtered by the HPF.

An angle of 400deg isn't a problem - it's the same as (40 + 360)deg, so it means it's just drifted a long way in that time.

I'd definitely remove the HPF. An LPF of 50Hz will be fine for most applications. The ADC itself will have a lot of bearing on the overall quality of the system and I have my doubts about the quality of the ones on microcontrollers (at least for this application)... some experimentation (maybe a precision buffer stage too? maybe an audio expert can suggest something here) will be required.

Because I'm lazy, I usually just get the chips with a built-in ADC and I can talk to them over SPI. It's about a \$7 to \$10 premium per device, but you'll pay the same for a really qood quality ADC anyway.

-- Damien

Hello damien,

My whole justification for calculating the angle is to calibrate the actual gyroscope scale. And yes, it is being used for a motion detection application.

Could you please elaborate on:

Quote:
An angle of 400deg isn't a problem - it's the same as (40 + 360)deg, so it means it's just drifted a long way in that time.

Why is this not a problem? Is there any way to compensate for the drift so that the bottom spikes are close to zero? The only conclusion that I've come to is that the frequency range of the drift is within the frequency range of the signal itself when there is motion. For some reason, I don't regonise the drift in the gyro time data. Is this expected?

I'm not necessarily interested in the position, I'm moreso interested in the amount by which to scale the gyro data. So would it be foolish for to simply divide the gyro data by a factor of 4.44 to then yield 90 degrees on the rotation?

Thanks once again.

tabshizzle wrote:
The only conclusion that I've come to is that the frequency range of the drift is within the frequency range of the signal itself when there is motion. For some reason, I don't regonise the drift in the gyro time data. Is this expected?

In either case, I'd still remove the HPF and implement it in software, if you have to :)

I'm trying to get my head around "drift" in your context. If you're talking about drift in the plot, then yes, the HPF is indeed filtering out real actual motions, since they're appearing as rather low frequencies.

As far as the bias drift on the actual sensor readings, then it shouldn't be changing over the very short time scale of a 90deg swing. As far as getting rid of that, you can:

1. Sit the device still, take the steady state of the readings as the bias on the sensor.
2. Integrate as follows:

```angle = angle + (sensor_reading - bias) * dt;
```

At (near) constant temperature, the bias shouldn't vary too much in the time it takes to turn 90deg, or even over a few minutes.

Quote:

I'm not necessarily interested in the position, I'm moreso interested in the amount by which to scale the gyro data. So would it be foolish for to simply divide the gyro data by a factor of 4.44 to then yield 90 degrees on the rotation?

It's not a bad starting point If you're doing motion detection (or, say, rollover detection for a car), then chances are that you're really interested in the relative amplitude of the motion rather than the absolute value of the motion itself.

If not (i.e. you need absolute changes in angle), then I'd go back to removing the HPF, calibrating for bias so that you're not filtering out the real motions.

-- Damien

Hey damien,

You're right, I don't see very much bias drift at all in the sensor reading. However, on calculating the angular position, there is a very clear downward slope.

Unfortunately, I'm not sure if removing the analog HPF is an option. :(

One last thing that I would like to confirm with you. I am attempting the D/A conversion by:

`((DigitalSample/4095)*Vdd - Vzero) /sensitivity`

However, I sometimes receiver a greater angular velocity than the max specified rate in the datasheet (+-1500deg/sec). Is there any error that you notice in the above conversion?

The above phenomenon is my whole reason for calibrating the scale of the gyroscope signal by determining the scale factor via rotating the instrument 90 degrees.

Thanks again for your help.

tabshizzle wrote:

One last thing that I would like to confirm with you. I am attempting the D/A conversion by:

`((DigitalSample/4095)*Vdd - Vzero) /sensitivity`

Is Vzero calculated with the (x/4095*Vdd) scale factor? If not, this will cause some problems as there is a bias introduced into the reading. Otherwise, try:

```processed_sample = (raw_sample - unscaled_bias_from_adc) * (Vdd / 4095 / sensitivity);
```

In this case, the sensitivity is in (V / (deg/s))). Sometimes, you'll see a figure in ((deg/s) / V). Check also that the voltage of the ADC is referenced from (0 - Vdd) - some ADC will have a bandgap reference (e.g. 0 - 2.6V or something like that).

Normally, I'd also suspect integer calculations, but the graph doesn't look like that's the problem, and looks like you're doing MATLAB anyway :). If it's in C, make sure that the scale factor multiples are all floating point values for this sort of calculation, unless you go to the effort of carefully scaling integers to avoid underflow/overflow.

-- Damien

Hey damien,

Vzero is simply a number that I extracted from the datasheet. I personally don't see any bias since the zero is actually at zero.

And yes, I'm doing most of the signal processing in Matlab itself. That's a good point you make about scaling in C!

I'm sure that the ADC reference is the power supply otherwise I think that would contribute to the zero not being actually zero.

If you want to see something weird, check out what I'm getting. Although the datasheet says that the gyroscope full scale is +- 1500 degress/sec, the actual saturation levels are way different and not even close to being symmetrical! :shock:

That's ^ the result I get from sending the gyroscope into saturation.

As someone who has never used Gyros or Accelerometers, I have a question about reducing the noise and drift. Can one average the outputs of identical units to cancel some of the noise and drift? If so, what about the mechanical orientation of each one with respect to the others? How critical is that?

Rick

Quote:

As someone who has never used Gyros or Accelerometers, I have a question about reducing the noise and drift. Can one average the outputs of identical units to cancel some of the noise and drift? If so, what about the mechanical orientation of each one with respect to the others? How critical is that?

I have a partial but incomplete answer to this question. We'll leave aside issues of mechanical orientation for a later post and focus on having multiple sensors.

I suppose the bigger question is whether multiple cheap sensors outperform one excellent sensor. I suspect the answer will be application dependant.

To explain, let's use a simple sensor model of a gyro.

```rate_measured = rate_truth + temperature_bias + fixed_bias + time_varying_bias + white_noise
```

Where:
* rate_truth is the true angular rate
* temperature_bias is the change in output with change in temperature
* fixed_bias, (randomly) time_varying_bias and white_noise are exactly as they sound.

Multiple sensors will undoubted reduce the amount of white noise and is therefore beneficial.

The jury is out on temperature bias and fixed bias (both of which can be calibrated for anyway). The answer will depend on whether devices from a single family tend to have (for example) a similar temperature curve, or have independent temperature curves. If the curves are independent, then multiple sensors will help. If not, then there won't be much benefit.

The real trick is with the randomly time-varying bias. Although it is complex to model, in practice a good approximation of how the bias varies is a random walk (which is what we do at work). Essentially, a random walk is a cumulative addition of white noise. The longer it goes, the more uncertain it is.

So, consider that you have two sensors in the array, which are added together and divided, assuming only time_varying_bias exists:
1. Each sensor time step has a standard deviation of sigma, and a variance of sigma_squared.
2. When added together, the variance of the time step is both added together, hence the variance is (2 * sigma_squared)
3. Since the two are averaged, the variance of time time step will be (sigma_squared/2), or std = (sigma / sqrt(2))

Hence, adding sensors will reduce the step size of the random walk, which is critical to long-term navigation, but it's diminishing returns - it looks like is a 1/sqrt(n) improvement on the step size of the random walk.

I haven't done the experiment, but maybe it's worth putting on 10 of these compared to one of these?

There is also another factor I am yet to consider - motion. The biases may become observable under motion (I haven't done the maths yet one way or another), as all sensors should be measuring the same physical quantity, but the biases will be different. I haven't seen any techniques covering this, but I think it might be interesting to find out!

-- Damien

RickB wrote:
If so, what about the mechanical orientation of each one with respect to the others? How critical is that?

Mechanical orientation can be both a blessing and a curse, but far more curse than blessing.

So, what's the blessing?

Well, it's much of a curse as a blessing. Since the sensors are not perfectly co-located, there will be a lever arm effect between the two sensors. Therefore, any rotational motion will couple into velocity, which will cause a measurement on the accelerometer - see p59 of this document for the equations.

The good news out of that is that you can exploit this information - some smart chaps worked out that they could measure angular rate indirectly using accelerometers scattered around a car (since they will measure both acceleration and angular velocity coupled with their distance from each other), forgoing the need for gyros which are the most expensive part of the inertial system (for example, we use accelerometers that are about \$10 per axis. The "matching" gyros are \$50 per axis). Nice!

So what's the curse?

The bad news is that misalignment (where the sensors are not precisely 90deg to each other) will couple into errors.

For example, if the z-axis accelerometer is not perfectly aligned 90deg to the x- and y-axes, it will measure most of z (say, 99%), but also a few percent of x- and y- (say, 2%). This is usually specified in the accelerometer datasheet. It means that this will directly couple into any estimates or pitch and roll.

Similarly for gyros, any misalignments will start picking up rotation rates in the other two axes which, when integrated, will give you erroneous pitch, roll and yaw estimates.

By careful calibration, one can measure the cross-axis sensitivity in a lab and compensate for it in the field, as many commercial IMUs do.

Whether this is really a problem depends on your application. It might not matter for a small UAV, or for a camera, or for some body-worn sensor, but for high precision applications such as inertial navigation, it is critical (position errors will grow with t^3 for misalignment in gyros).

-- Damien

Wonderful peek into some of the issues with drift and noise. Thank you!

And FYI, FAQ section a), last sentence, says, "It's marking talk ..." Should be "marketing" instead of "marking".

Respectfully,
Alan

alanair wrote:
Wonderful peek into some of the issues with drift and noise. Thank you!

And FYI, FAQ section a), last sentence, says, "It's marking talk ..." Should be "marketing" instead of "marking".

Respectfully,
Alan

Fixed the typo... thanks for your feedback :) It's appreciated.

-- Damien