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 = Accelerometer.GetDefault();
accelerometer = Windows.Devices.Sensors.Accelerometer.getDefault();
private void ScenarioEnable(object sender, RoutedEventArgs e)
{
    if (_accelerometer != null)
    {
        // Establish the report interval
        _accelerometer.ReportInterval = _desiredReportInterval;

        Window.Current.VisibilityChanged += new WindowVisibilityChangedEventHandler(VisibilityChanged);
        _accelerometer.ReadingChanged += new TypedEventHandler<Accelerometer, AccelerometerReadingChangedEventArgs>(ReadingChanged);

        ScenarioEnableButton.IsEnabled = false;
        ScenarioDisableButton.IsEnabled = true;
    }
    else
    {
        rootPage.NotifyUser("No accelerometer found", NotifyType.StatusMessage);
    }
}
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.

async private void ReadingChanged(object sender, AccelerometerReadingChangedEventArgs e)
{
    await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
    {
        AccelerometerReading reading = e.Reading;
        ScenarioOutput_X.Text = String.Format("{0,5:0.00}", reading.AccelerationX);
        ScenarioOutput_Y.Text = String.Format("{0,5:0.00}", reading.AccelerationY);
        ScenarioOutput_Z.Text = String.Format("{0,5:0.00}", reading.AccelerationZ);
    });
}
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.

private void ScenarioEnable(object sender, RoutedEventArgs e)
{
    if (_accelerometer != null)
    {
        Window.Current.VisibilityChanged += new WindowVisibilityChangedEventHandler(VisibilityChanged);
        _accelerometer.Shaken += new TypedEventHandler<Accelerometer, AccelerometerShakenEventArgs>(Shaken);
        ScenarioEnableButton.IsEnabled = false;
        ScenarioDisableButton.IsEnabled = true;
    }
    else
    {
        rootPage.NotifyUser("No accelerometer found", NotifyType.StatusMessage);
    }
}
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.

async private void Shaken(object sender, AccelerometerShakenEventArgs e)
{
    await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
    {
        _shakeCount++;
        ScenarioOutputText.Text = _shakeCount.ToString();
    });
}
var onShaken = (function () {
    var shakeCount = 0;

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