Inspecting the accelerometer sensor

We are going to build an inspector of the accelerometer sensor. We will display the values of the 3 axises – X, Y and Z.

Before getting into code, you may want to check the demo in the following link.

http://mztests.herokuapp.com/motion/

The PhoneGap approach

First, here we have the PhoneGap approach. It is like most PhoneGap API call with success callback, fail callback and options parameters.

 1var watchAcceleration = function() {
 2  this.watchID = navigator.accelerometer.watchAcceleration(
 3  //success callback:
 4  function(acceleration){
 5    this.acceleration = acceleration;
 6  },
 7  // error callback:
 8  function(){
 9    // error on getting acceleration.
10  },
11  // options:
12  { frequency: 3000 });
13};

http://docs.phonegap.com/en/1.2.0/phonegap_accelerometer_accelerometer.md.html

The web standard approach

1window.addEventListener('devicemotion', function (e) {
2  this.acceleration = e.acceleration;
3};

The code example

We use a list to display the value history.

1<ul id="x" class="history">
2  <li>No Data Yet</li>
3</ul>

We use an array to store the history of the value. And set a limit count to the array.

 1app.xValues = [];
 2window.addEventListener('devicemotion', function (e) {
 3  app.xValues.push(e.acceleration.x);
 4  var listLimit = 15;
 5  if (app.xValues.length > listLimit) {
 6    app.xValues.splice(0, 1); // remove the old records when list too long.
 7  }
 8
 9  app.view.update();
10});
 1app.view = {}
 2app.view.update = function(){
 3  this.renderHistory($('#x'), app.xValues);
 4}
 5
 6app.view.renderHistory = function(element, data) {
 7  $(element).empty();
 8  for (var i = app.xValues.length - 1; i >= 0; i--) {
 9    $(element).append("<li>" + Math.floor(data[i]*1000) + "</li>");
10  };
11}

Note that this code only handled the X value. There are Y and Z value in accelerometer sensor.

What’s next? We’re going to take a look at “Accelerometer value bar chart”.

overlaied image when clicked on thumbnail

Makzan | Mobile web app dev with phonegap | Table of Content