Showing posts with label gyroscope. Show all posts
Showing posts with label gyroscope. Show all posts

Thursday, June 20, 2013

Tap detection supported by the gyroscope


Once upon a time I made a Londroid presentation that briefly mentioned the possibility of detecting taps on the phone's body with an accelerometer (it is in slide 31). You may rightly ask, why do you want to detect taps with the accelerometer when there is the touchscreen? First, the touchscreen may be switched off by the screensaver or the user may have deactivated it because he or she is in a call or put the phone into a position where the touchscreen may be touched unintentionally. Then the user may want to tap the back of the phone. Lastly, the user may be interested in the strength of the tap, not only its location or the fact that the tap happened.

Let's recall that graph in that old Londroid presentation.



The graph shows the absolute value of the acceleration vector while the phone's body was tapped twice. The base rate is the gravity acceleration (about 10 m/sec^2) and the acceleration caused by the taps was added (in the actual configuration, subtracted) from the gravity acceleration, resulting two characteristic spikes.

But where was the phone's body tapped? By looking solely on the accelerometer's data, I don't think there is a way to find it out. But fortunately we have other sensors and the gyroscope is particularly relevant. Here is the well-known image of the sensor axes in Android.



In case of the gyroscope, the sensor measures rotation around the axes. If you tap the device in the right lower corner, we can expect a short rotation around the x and y axes if the phone supported by a reasonably flexible base (e.g. a human hand and not a block of granite).

But can this be really detected? I made a series of measurements to prove it. Note here that I was just interested in the theoretical possibility and did not want to do a product-grade implementation. So I tested only on my Galaxy Nexus.

First here is the absolute acceleration value for 3 consecutive taps.




As expected, the time of the tap can be safely detected. These taps were all in the lower right corner so let's see what the gyroscope measured along the x and y axes.

X axis, just for two taps:



Y axis, just for two taps:



As you can see, the taps are detected by the gyroscope too as short rotations. In case of both axes, there was a spike of positive rotation velocity first.

Now let's see what happens, if we tap the lower left corner.

X axis, just for two taps:



Y axis, just for two taps:



As you see, the X graph has the same character but the form of the Y graph has changed. Instead of a marked positive spike, there is a small negative spike, followed by a positive spike.

Let's see if the experience is repeated in the upper left corner.

X axis, just one tap:


Y axis, just one tap:



Now the character of the spikes on both axes changed. A small positive spike is followed by a large negative spike.

This is not a kind of movement the gyroscope was designed for so it is premature to state that this waveform pattern will be exactly the same for all the Android devices sporting gyroscope out there. But I found these measurements convincing enough to support the statement that it is possible to implement rudimentary tap location using only the accelerometer and the gyroscope in the device.

Tuesday, June 19, 2012

Universal orientation, gravity and motion acceleration sensor

We have seen a number of fusion possibilities for 2 sensors.


Time has come to put all of these together and to take a step toward the Holy Grail of sensor processing. We want a sensor that measures gravity, motion acceleration and orientation reliably, no matter what the circumstances are. If we achieve this, then we have a good basis for the much researched in-door navigation problem because the linear acceleration may be used for step counting while the orientation can be used to calculate the vector of movement. Errors will accumulate but if we have occasional reference points like WiFi beacons, reasonably good results can be achieved.


So what prevents us realizing this vision? We already obtained a pretty reliable motion acceleration estimation from the accelerometer-gyroscope fusion. The orientation is the thing we don't have. Using the compass-accelerometer fusion we can eliminate the tilt problem. If we throw in the gravity calculation from the accelerometer-gyroscope fusion and use the gravity estimation instead of the raw accelerometer data for the compass tilt compensation then we have also compensated the motion acceleration. The only thing we don't have is the effect of external magnetic fields which may fool the compass and can be pretty nasty in-door in the presence of household appliances, large transformators or other electric machinery. That we will compensate with a compass-gyroscope fusion.


The idea of the compensation of the external magnetic field using the gyroscope is very similar to the compensation of the motion acceleration. If we assume that no external magnetic field is present (beside the Earth's magnetic field), we just use the compass data (and then post-compensate against tilt by the gravity vector which needs accelerometer-gyroscope fusion). If we suspect that there may be external magnetic field present, we use the gyroscope rotation data to rotate a previous, trusted compass vector (that is supposed to measure only the Earth's magnetic field) and use that as compass estimation. The difference between this compass estimation and the measured compass value is the estimation for the external magnetic field.


The trick is the detection whether an external magnetic field may be present. In this prototype the same trick was used as with the accelerometer: if the length of the compass vector is too long or too short compared to the reference measurement, then we have an external magnetic field to compensate.

Here is the summary of the sensor fusions used in this prototype:


  • Accelerometer-gyroscope fusion provides gravity and motion acceleration.
  • Compass-gravity fusion provides compass tilt compensation. The gravity is already a derived measurement coming from the accelerometer-gyroscope fusion.
  • Compass-gyroscope fusion provides orientation and external magnetic field.
Click here to download the example program.

The example program starts with a complex stationary and dynamic calibration process. When stationary, it measures the reference gravity and magnetic field values. In this stage it is very important that the device is not subject to motion acceleration or external magnetic field (beside the Earth's magnetic field). In the dynamic calibration phase we calculate the bias of the compass. We do this by instructing the user to rotate the device and measuring compass vectors in each special position. These are supposed to be points on a sphere. Once we collected the measurement points, we calculate the center of the sphere by solving a set of linear equations. The Jama package was incorporated into the example program for matrix manipulations.

Once the calibration is finished, the algorithm outlined above is executed. The measurement data is visualized in a 2D coordinate system - the z coordinate is not drawn. This is just my laziness, I did not take the effort to implement a 3D visualization engine. It is important to note, however, that the motion acceleration (yellow) and the external magnetic field (cyan) vectors are really 3D, they are just not drawn as such. The white vector is the final orientation compensated against tilt, motion acceleration and external magnetic field.




The prototype does have limitations. While it survives pretty nicely short-term disturbances from external magnetic fields (try with a small magnet), in longer term (e.g. after 5-10 minutes) it gets properly lost. For example when riding the Budapest underground there are strong and varying magnetic fields generated by the train's traction motors during the entire journey. If the compensation algorithm picks up a wrong reference vector, it may get lost for the rest of the journey until it is able to pick up the Earth's undisturbed magnetic field.

Friday, February 10, 2012

Example application for accelerometer/gyroscope processing on Android

In the previous parts we have seen how to simulate the gravity vector with the gyroscope if the accelerometer is not able to measure gravity correctly (because it is subject to motion acceleration too beside the gravity acceleration) and how to update this simulated gravity vector from the accelerometer to prevent the accumulation of measurement errors. At the end of the previous post we had a gravity vector which was normally taken from the accelerometer but our algorithm switched to gyroscope simulation automatically when needed.

We need just one more step to enable cool applications and that step is very evident. If you remember my Droidcon 2011 presentation (slide 24), the acceleration measured by the accelerometer is the sum of gravity and motion acceleration. If both are present, they cannot be separated in the general case without additional sensor input. But now we have the gravity acceleration which is reasonably exact even if the accelerometer is subject to motion acceleration too. This means that we can extract the motion acceleration by subtracting the simulated gravity acceleration from the acceleration measured by the accelerometer.

This opens the way for applications based on dynamic movements much like the Wii games with Motion Plus accessory (which actually do the same as the Motion Plus accessory is really just a 2+1 axis gyroscope).

The example program can be downloaded from here.

After all these simulation script, let's see something hands-on. The example program is the implementation of all these ideas we have seen so far. You need an Android phone with gyroscope to test it. The gyroscope processing algorithm is implemented in SamplingService.java. GyroAccelActivity is really doing only visualization, getting callbacks from SamplingService.

When started, the service enters the calibration state. This state is necessary to get a good fix of the initial gravity vector so the device should not be moved when calibrating. The initial gyroscope drift experienced on my Nexus S also ceases during the calibration period.

Then the service enters the measuring state and implements everything we discussed so far. It samples the accelerometer and the gyroscope paralelly, simulates the gravity vector if it finds out that the accelerometer is probably subject to motion acceleration and calls back the activity with the calculated motion acceleration vector. The acceleration is shown as movement of a large white ball (quite ugly, actually). The x and the y components of the motion acceleration move the ball horizontally and vertically while the size of the ball is calculated from the z component of the motion acceleration.

Note that the motion acceleration is expressed in the coordinate system of the device itself, so you may get some unexpected result if the device is not parallel to the floor surface. As we have the gravity vector, rotating the motion acceleration vector to the Earth's coordinate system is simple exercise (took me several days to get it right ;-)). We calculate two rotations (around z and y axes) to rotate the gravity vector into the z axis. At the same time we rotate the motion acceleration vector with the same rotations. This yields a normalized motion acceleration vector that would have been measured if the device were parallel to the surface.

If you are done with playing the ball, you will notice that analyzing these 3D acceleration vectors are not trivial. You can try setting the SamplingService.DEBUG field to true, then the application produces the usual /sdcard/capture.csv file (beware, it can be large) that you can download to your computer and visualize with this Sage script.


Wednesday, January 25, 2012

Compensating accelerometer data with the gyroscope

In the previous post we have seen, how we can simulate the rotations of the gravity vector (thus measuring the exact tilt) with the help of the gyroscope. During that measurement we moved the device only slowly to validate the claim that the gyroscope is able to track the gravity vector for a certain period of time. We were aware of the fact that measurement errors for this type of measurement will eventually accumulate and therefore we have to pick the correct gravity vector time to time.

In this post we go one step further. We will use the gyro-based simulated gravity vector only if the accelerometer does not provide us with reliable gravity vector measurement (because the device is subject to motion acceleration too). But how to figure out if the gravity measurement of the accelerometer is reliable or not? Let's see the picture below which is shows the absolute value (the length) of the accelerometer's output vector as a function of sample count when the device is subject to a "tennis-like" movement. This means that the device is held in one hand and I simulated as if it was a tennis racquet. The device rotates but is also subject to a significant motion acceleration.



We have problem when the absolute value of the acceleration is significantly larger (or smaller) than 1 g (about 10 m/s^2). This means that when the absolute value of the acceleration vector is close to 1g, we can be quite sure that there is no motion acceleration and we have reliable gravity vector measurement.

This detection method is not foolproof, however. We can construct gravity and motion acceleration vector arrangements so that the length of the resulting vector is 1 g, still it points to completely wrong direction compared to the gravity vector. The keyword is "construction". Even though these arrangements are possible, it is very unlikely that they persist for a long time during motion.

So the gyro compensation algorithm is the following:

  • If the absolute value of the acceleration vector is significantly larger or smaller than 1g, ignore it and use the gyro-simulated gravity vector.
  • If the absolute value of the acceleration vector is close to 1g but differs significantly from the gyro-simulated vector then start counting these cases. If this case happens 5 times consecutively then update the gyro-simulated vector from the acceleration vector and use that.
Otherwise update the gyro-simulated vector from the acceleration vector and use this value to calculate the gravity vector.

Let's see now our racquet swing. The samples were taken with the Android application attached to the previous post, the analysis was done with this Sage script. The Sage script takes the samples from capture.csv file - you can easily change that in line 456. Blue line is the collection of 3D acceleration vectors from the accelerometer, red line is the gyro-compensated gravity vector (taken from the accelerometer if there is no motion, simulated with the help of the gyroscope if motion acceleration is detected).



As you can see, the blue line is everywhere. Actually it goes out of the coordinate system as the Nexus S has its accelerometer limited at 2g - that's why you see the acceleration curve turned into straight lines at the fastest points of the movement. The red line, however, follows the curve of the device's tilt nicely and eventually ends almost where the acceleration's blue line does. Then it gets compensated by the accelerometer's gravity vector measurement - no cumulative errors.

There's more to come, just stay tuned.

Saturday, January 21, 2012

Measuring movement with accelerometer and gyroscope

Santa Claus brought me a present and that sadly means retiring of my trusty Nexus One. Not that the phone has any problem - it still functions perfectly. As Google does not update the Nexus One anymore with new software release, I had to change. And the winner is - well, not the Galaxy Nexus, that's too expensive. I chose a Nexus S because of its attractive price, its update path toward Android 4.x (it is actually the cheapest option today of an Android 4 phone) and its built-in gyroscope.

I wanted to put my hand on a gyroscope-equipped phone for a long time. I discussed in length the problems of using only the accelerometer when identifying movements in my Droidcon 2011 presentation and I hinted that additional sensors could be used to compensate for the motion acceleration that is added to the gravity acceleration and is impossible to separate in the general case. That's what I am aiming to do with the gyroscope in this series of posts.

First let's see the problem. As you can see in slides 23 and 24 of the Droidcon 2011 presentation, there is a problem if the accelerometer is subject to gravity and motion accelerations at the same time. These are impossible to separate in the general case which corrupts both use cases. If the accelerometer is used to measure gravity (e.g. to figure out the device tilt), any motion acceleration distorts the measured tilt. If the accelerometer is used to measure motion acceleration and the exact direction of the gravity acceleration is not known, it is impossible to subtract it and the components of the motion acceleration is impossible to calculate. We need another sensor to acquire additional information to separate the gravity and motion components.

Gyroscope sensor is somewhat rare in today's Android phones. Nexus S was the first to have gyro sensor and since then some high-end phones like Galaxy S II got the sensor. If you want to play with gyro, check, whether your phone has the sensor.

The gyroscope measures angular speed along the 3 axes. As the SensorManager in Android delivers the sensor samples along with timestamps measured in nanoseconds, it is possible to calculate the rotation angle in radian by multiplying the angular speed with the time difference between the current and the previous sample. This means that we know the rotation angles along the 3 axes from the previous to the current gyroscope sample.

Thus the gyroscope can be used to replace the accelerometer when the accelerometer data is distorted by motion acceleration. If we have a reliable gravity vector measurement, we can use the rotation angles measured by the gyroscope to rotate this vector to its new position. As the gyroscope is not subject to motion acceleration, the gravity vector updated by the gyroscope rotation angles will not be affected by the motion acceleration.

The example program is available here.

How exact could this tracking be? I have made a simple sensor sampling application that samples the accelerometer and the gyroscope paralelly. If you try it out, please check that both the accelerometer and the gyroscope sensors' name is displayed - this means that they are available. Move the device only slowly - we don't want motion acceleration in this measurement. The sample file is saved in the file capture.csv on the SD card - typically /sdcard/capture.csv. Fetch this file and you can analyse it with this Sage script called gyro.py. This script expects the measurement data file in the current directory with the name of agx.csv - you can easily change it in line 244.

As the figure below demonstrates, the real gravity vector (blue line) is pretty close to the gravity vector simulated with the gyroscope (red line). Eventually the cumulative errors will make the simulated vector diverge from the real gravity vector - more about later.