Retrieving accelerometer data in simple apps
Collapse the table of content
Expand the table of content

Retrieving accelerometer data in simple apps (Windows Runtime apps)

An app can track changes in Accelerometer class readings and the Shaken event, by registering for the respective event notifications. An app can also poll for the current sensor reading by using the GetCurrentReading method.

The following code examples demonstrate how to retrieve the default accelerometer and then register an event handler to receive ReadingChanged notifications when the sensor issues a new reading.

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

function enableReadingChangedScenario() {
    if (accelerometer) {
        // Set the reportInterval to enable the sensor events
        accelerometer.reportInterval = reportInterval;

        document.addEventListener("msvisibilitychange", msVisibilityChangeHandler, false);
        accelerometer.addEventListener("readingchanged", onDataChanged);
        document.getElementById("scenario1Open").disabled = true;
        document.getElementById("scenario1Revoke").disabled = false;
    } else {
        WinJS.log && WinJS.log("No accelerometer found", "sample", "error");

The ReadingChanged event handler then receives the new values for the x-axis, y-axis, and z-axis as shown in the following example.

function onDataChanged(e) {
    var reading = e.reading;

    document.getElementById("eventOutputX").innerHTML = reading.accelerationX.toFixed(2);
    document.getElementById("eventOutputY").innerHTML = reading.accelerationY.toFixed(2);
    document.getElementById("eventOutputZ").innerHTML = reading.accelerationZ.toFixed(2);

Apps can also register for the Shaken event handler to receive notifications when the sensor indicates that the device has been shaken. Here are examples.

function enableShakenScenario() {
    if (accelerometer) {
        document.addEventListener("msvisibilitychange", msVisibilityChangeHandler, false);
        accelerometer.addEventListener("shaken", onShaken);
        document.getElementById("scenario2Open").disabled = true;
        document.getElementById("scenario2Revoke").disabled = false;
    } else {
        WinJS.log && WinJS.log("No accelerometer found", "sample", "error");

Take the appropriate action when the Shaken event is received, as shown here.

var onShaken = (function () {
    var shakeCount = 0;

    return function (e) {
        document.getElementById("shakeOutput").innerHTML = shakeCount;



© 2016 Microsoft