Quickstart: Responding to user movement with the accelerometer (Windows Store apps using JavaScript and HTML)

Language: JavaScript and HTML | VB/C#/C++ and XAML
1 out of 3 rated this helpful - Rate this topic

You can use the accelerometer to respond to user movement in an app written in JavaScript. An app based on an accelerometer typically uses only one or two axes for input. However, it may also use the shake event as another input source.

Objective: After completing this quickstart you will understand how to use the accelerometer to detect changes in movement.

Prerequisites

You should be familiar with HTML, JavaScript, and events.

The device that you're using must have an accelerometer.

Time to complete: 15 minutes.

Instructions

1. Open Microsoft Visual Studio Express 2012 for Windows 8

Open an instance of Microsoft Visual Studio Express 2012 for Windows 8.

2. Create a new project

To create a new project, click File > New Project. Under Templates, select Blank Application from the JavaScript project types.

3. Insert the app JavaScript

Open your project's default.js file and replace the existing code with the following.


// For an introduction to the Blank template, see the following documentation:
// http://go.microsoft.com/fwlink/p/?linkid=232509
(function () {
    "use strict";
    var accelerometer;

    var app = WinJS.Application;

    // This function responds to all app activations.
    app.onactivated = function (eventObject) {
        if (eventObject.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) {
            if (accelerometer == null) {
                accelerometer = Windows.Devices.Sensors.Accelerometer.getDefault();

                // Establish the report interval
                var minimumReportInterval = accelerometer.minimumReportInterval;
                var reportInterval = minimumReportInterval > 16 ? minimumReportInterval : 16;
                accelerometer.reportInterval = reportInterval;

                // Establish the event handler
                accelerometer.addEventListener("readingchanged", onDataChanged);
            }
            WinJS.UI.processAll();
        }
    };

    // This function is called each time an accelerometer event
    // is fired by the driver.
    function onDataChanged(e) {
        var reading = e.reading;
        var accelX = reading.accelerationX;
        var accelY = reading.accelerationY;
        var accelZ = reading.accelerationZ;

        id('eventOutputX').innerHTML = accelX.toFixed(2);
        id('eventOutputY').innerHTML = accelY.toFixed(2);
        id('eventOutputZ').innerHTML = accelZ.toFixed(2);
    }

    // This function is invoked within onDataChanged to
    // retrieve the given identifier from the HTML document.
    function id(elementId) {
        return document.getElementById(elementId);
    }

    app.start();
})();


4. Insert the app HTML

Open the file default.htm and copy the following HTML into this file (replacing its original contents).


<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Application1</title>

    <!-- WinJS references -->
    <link href="//Microsoft.WinJS.0.6/css/ui-dark.css" rel="stylesheet">
    <script src="//Microsoft.WinJS.0.6/js/base.js"></script>
    <script src="//Microsoft.WinJS.0.6/js/ui.js"></script>

    <!-- Application1 references -->
    <link href="/css/default.css" rel="stylesheet">
    <script src="/js/default.js"></script>
</head>
<body>
    <div class="item" id="scenarioOutput">
    X: <a id="eventOutputX">no data</a>
    <br />
    Y: <a id="eventOutputY">no data</a>
    <br />
    Z: <a id="eventOutputZ">no data</a>
    <br />
    </div>
</body>
</html>


5. Build, deploy and run the app

Press F5 (or click Debug > Start Debugging) to build, deploy, and run the app.

6. Stop the app

  1. Press ALT+Tab to return to Visual Studio.
  2. Press Shift+F5 (or Debug > Stop Debugging) to stop the app.

Summary and next steps

The previous example demonstrates how little code you'll need to write in order to integrate accelerometer input in your app.

The app establishes a connection with the default accelerometer in the onactivated function. This occurs on the following line.


accelerometer = Windows.Devices.Sensors.Accelerometer.getDefault();

The new accelerometer data is captured in the onDataChanged function. Each time the sensor driver receives new data from the sensor, it passes the values to your app by using this function (or event handler). The app registers this event handler on the following line.


accelerometer.addEventListener("readingchanged", onDataChanged);

These new values are written to the screen via updates to the DOM elements shown below.


    <div class="item" id="scenario1Output">
    X: <a id="eventOutputX">no data</a>
    <br />
    Y: <a id="eventOutputY">no data</a>
    <br />
    Z: <a id="eventOutputZ">no data</a>
    <br />
</div>

The app establishes the report interval within the onactivated function. This code retrieves the minimum interval supported by the device and compares it to a requested interval of 16 milliseconds (which approximates a 60-Hz refresh rate). If the minimum supported interval is greater than the requested interval, the code sets the value to the minimum. Otherwise, it sets the value to the requested interval.


var minimumReportInterval = accelerometer.minimumReportInterval;
var reportInterval = minimumReportInterval > 16 ? minimumReportInterval : 16;
accelerometer.reportInterval = reportInterval;


If you're writing a simple app, the next steps would typically involve integrating accelerometer input with graphic output.

For example, you could create a simple "level" app that renders a colored circle in the center of the webpage when the device is level, but alters the circle's position in response to movement detected by the accelerometer along the x-axis and y-axis.

Related topics

Accelerometer class
Accelerometer Sample

 

 

Build date: 10/26/2012

Did you find this helpful?
(1500 characters remaining)
© 2013 Microsoft. All rights reserved.