Accelerometer Accelerometer Accelerometer Accelerometer Class

Represents an accelerometer sensor.

This sensor returns G-force values with respect to the x, y, and z axes.

Syntax

Declaration

public sealed class Accelerometerpublic sealed class AccelerometerPublic NotInheritable Class Accelerometer

Remarks

Applications use the methods in this class to determine whether the sensor reading has changed or the device has been shaken.

Applications use the properties in this class to retrieve and adjust the sensor report interval.

Sensor data is provided relative to the device's fixed sensor coordinate system, and is independent of display orientation. For applications that rely on sensor data for input control or to manipulate elements on the screen, the developer must take current display orientation into account and compensate the data appropriately. For more info about the sensor coordinate system, see Sensor data and display orientation.

The following example demonstrates how a Windows Store app built with XAML and C# uses the GetDefault(Windows.Devices.Sensors.AccelerometerReadingType) method to establish a connection to an accelerometer. If no integrated accelerometer is found, the method will return a null value.

_accelerometer = Accelerometer.GetDefault();

The following example demonstrates how a Windows Store app built with XAML registers a ReadingChanged event handler.

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);
    }
}

The following example shows the ReadingChanged event handler.

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);
    });
}

Properties summary

Gets the device identifier.

Gets the maximum number of events that can be batched by the sensor.

Gets the minimum report interval supported by the accelerometer.

Gets or sets the transformation that needs to be applied to sensor data. Transformations to be applied are tied to the display orientation with which to align the sensor data.

Gets the type of accelerometer sensor the is represented by this object.

Gets or sets the current report interval for the accelerometer.

Gets or sets the delay between batches of sensor information.

Methods summary

Gets the current accelerometer reading.

Returns the default accelerometer.

Returns the default accelerometer of a specific type of sensor. The possible accelerometer sensors are defined by AccelerometerReadingType.

Events summary

Occurs each time the accelerometer reports a new sensor reading.

Occurs when the accelerometer detects that the PC has been shaken.

Properties

  • DeviceId
    DeviceId
    DeviceId
    DeviceId

    Gets the device identifier.

    public string DeviceId { get; }public string DeviceId { get; }Public ReadOnly Property DeviceId As string

    Property Value

    • string
      string
      string
      string

      The device identifier.

  • MaxBatchSize
    MaxBatchSize
    MaxBatchSize
    MaxBatchSize

    Gets the maximum number of events that can be batched by the sensor.

    public uint MaxBatchSize { get; }public uint MaxBatchSize { get; }Public ReadOnly Property MaxBatchSize As uint

    Property Value

    • uint
      uint
      uint
      uint

      The maximum number of batched events.

    Remarks

    A sensor may not support batched data collection. In that case, this property will be 0. Otherwise, this determines the maximum number of events the sensor can gather before submitting them. This in turn will determine the maximum supported ReportLatency. The maximum latency equals the ReportInterval times the MaxBatchSize. For more information about sensor batching, see Sensors.

  • MinimumReportInterval
    MinimumReportInterval
    MinimumReportInterval
    MinimumReportInterval

    Gets the minimum report interval supported by the accelerometer.

    public uint MinimumReportInterval { get; }public uint MinimumReportInterval { get; }Public ReadOnly Property MinimumReportInterval As uint

    Property Value

    • uint
      uint
      uint
      uint

      The minimum ReportInterval supported by the sensor.

  • ReadingTransform
    ReadingTransform
    ReadingTransform
    ReadingTransform

    Gets or sets the transformation that needs to be applied to sensor data. Transformations to be applied are tied to the display orientation with which to align the sensor data.

    public DisplayOrientations ReadingTransform { get; set; }public DisplayOrientations ReadingTransform { get; set; }Public ReadWrite Property ReadingTransform As DisplayOrientations

    Property Value

    Remarks

    This property provides these improvements:

    • Differences in the sensor data on landscape-first devices versus portrait-first devices are no longer important.
    • Easily port existing sensor-based apps that were written for landscape-first devices to portrait-first devices and vice-versa.
    • Allows handling of display orientation changes. You can align the sensor data with the current orientation by updating the sensor’s ReadingTransform to match the current display orientation.
    • Allows aligning sensor data with a display orientation that is different from the current display orientation.
  • ReadingType
    ReadingType
    ReadingType
    ReadingType

    Gets the type of accelerometer sensor the is represented by this object.

    public AccelerometerReadingType ReadingType { get; }public AccelerometerReadingType ReadingType { get; }Public ReadOnly Property ReadingType As AccelerometerReadingType

    Property Value

  • ReportInterval
    ReportInterval
    ReportInterval
    ReportInterval

    Gets or sets the current report interval for the accelerometer.

    public uint ReportInterval { get; set; }public uint ReportInterval { get; set; }Public ReadWrite Property ReportInterval As uint

    Property Value

    • uint
      uint
      uint
      uint

      The current report interval.

    Remarks

    The report interval is specified in milliseconds.

    The report interval will be set to a default value that will vary based on the sensor driver’s implementation. If your app does not want to use this default value, you should set the report interval to a non-zero value prior to registering an event handler or calling GetCurrentReading(). The sensor will then attempt to allocate resources to satisfy the application’s requirements but the sensor also has to balance the needs of other apps using the sensor.

    Changes to the report interval after an event handler has been registered or GetCurrentReading() has been called may apply to the delivery of subsequent sensor readings.

    Conversely, when an application is finished with the sensor, it should explicitly return the sensor to its default report interval by setting it to zero. This is important for power conservation, especially when using a language that may keep the sensor object active for an indefinite period prior to garbage collection.

    The application should consult the MinimumReportInterval property prior to setting the report interval to ensure that the sensor can honor the requested report interval. Setting a value below the minimum supported interval will either trigger an exception or have undefined results.

    Although the application can set this value to request a particular report interval,the driver will determine the actual report interval, based on internal logic. For example, the driver might use the shortest report interval that is requested by any caller.

    Setting a value of zero requests the driver to use its default report interval. As with requesting a specific interval, the driver may choose a different interval based on other client requests and internal logic.

  • ReportLatency
    ReportLatency
    ReportLatency
    ReportLatency

    Gets or sets the delay between batches of sensor information.

    public uint ReportLatency { get; set; }public uint ReportLatency { get; set; }Public ReadWrite Property ReportLatency As uint

    Property Value

    • uint
      uint
      uint
      uint

      The delay between batches of sensor information in milliseconds.

    Remarks

    This property is in reference to the frequency of ReadingChanged events.

    Not all sensors support ReportLatency. If the sensor does not support this property, it will function the same as if you set this value to 0. Setting this value to 0 will use the default latency for the sensor.

    If you set ReportLatency to a value higher than the maximum supported latency, the sensor will use the maximum supported latency. However, this property will not change in value. The maximum possible ReportLatency equals the MaxBatchSize times the ReportInterval.

    Be aware that multiple applications could be dependent on a single sensor. Each of those applications can set a different value for ReportLatency. In this scenario, the sensor needs to try to accommodate the lowest value for ReportLatency. Because of this, the actual latency may not match the latency defined by this property in your application. This property corresponds to your ideal latency, which may not be the same latency on the sensor.

    For more information about sensor batching, see Sensors.

Methods

  • GetCurrentReading()
    GetCurrentReading()
    GetCurrentReading()
    GetCurrentReading()

    Gets the current accelerometer reading.

    public AccelerometerReading GetCurrentReading()public AccelerometerReading GetCurrentReading()Public Function GetCurrentReading() As AccelerometerReading

    Returns

    Remarks

    An application may use this method to poll the sensor for the current reading as an alternative to registering a ReadingChanged event handler. This would be the preferred alternative for an application that updates its user interface at a specific frame rate. Whether polling once or many times, the application must establish a desired ReportInterval. This informs the sensor driver that resources should be allocated to satisfy subsequent polling requests

    If the sensor is configured to support batch delivery, this method flushes the current batch and starts a new latency period. For more information about sensor batching, see Sensors.

    Before using the return value from this method, the application must first check that the value is not null. (If the value is null and you attempt to retrieve it, Windows will generate an exception.)

    The following example demonstrates how a Windows Store app built with XAML and C# retrieves the current reading for the three axes of the default accelerometer.

    private void DisplayCurrentReading(object sender, object args)
    {
        AccelerometerReading reading = _accelerometer.GetCurrentReading();
        if (reading != null)
        {
            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);
        }
    }
    

    The following example demonstrates how a Windows Store app built for Windows using JavaScript retrieves the current reading for the three axes of the default accelerometer.

    function getCurrentReading() {
        var reading = accelerometer.getCurrentReading();
        if (reading) {
            document.getElementById("readingOutputX").innerHTML = reading.accelerationX.toFixed(2);
            document.getElementById("readingOutputY").innerHTML = reading.accelerationY.toFixed(2);
            document.getElementById("readingOutputZ").innerHTML = reading.accelerationZ.toFixed(2);
        }
    }
    
  • GetDefault()
    GetDefault()
    GetDefault()
    GetDefault()

    Returns the default accelerometer.

    public static Accelerometer GetDefault()public static Accelerometer GetDefault()Public Static Function GetDefault() As Accelerometer

    Returns

    Remarks

    This method only returns values for an accelerometer that has been integrated into the computer by the manufacturer. A null value will be returned if the specified sensor is not available in the system.

    When a system is in Connected Standby, a call to the GetDefault(Windows.Devices.Sensors.AccelerometerReadingType) method will return immediately with a null result.

    The following example demonstrates how a Windows Store app built with XAML and C# used this method to establish a connection to the default accelerometer.

    _accelerometer = Accelerometer.GetDefault();
    

    The following example demonstrates how a Windows Store app built for Windows using JavaScript used this method to establish a connection to the default accelerometer.

    accelerometer = Windows.Devices.Sensors.Accelerometer.getDefault();
    
  • GetDefault(Windows.Devices.Sensors.AccelerometerReadingType)
    GetDefault(Windows.Devices.Sensors.AccelerometerReadingType)
    GetDefault(Windows.Devices.Sensors.AccelerometerReadingType)
    GetDefault(Windows.Devices.Sensors.AccelerometerReadingType)

    Returns the default accelerometer of a specific type of sensor. The possible accelerometer sensors are defined by AccelerometerReadingType.

    public static Accelerometer GetDefault(Windows.Devices.Sensors.AccelerometerReadingType readingType)public static Accelerometer GetDefault(Windows.Devices.Sensors.AccelerometerReadingType readingType)Public Static Function GetDefault(readingType As Windows.Devices.Sensors.AccelerometerReadingType) As Accelerometer

    Parameters

    Returns

Events

  • ReadingChanged
    ReadingChanged
    ReadingChanged
    ReadingChanged

    Occurs each time the accelerometer reports a new sensor reading.

    public event TypedEventHandler ReadingChangedpublic event TypedEventHandler ReadingChangedPublic Event ReadingChanged

    Remarks

    An application may register this event handler to obtain sensor readings. The application must establish a desired ReportInterval. This informs the sensor driver that resources should be allocated to satisfy the requirements of the application.

    The following example demonstrates how a Windows Store app built with C# and XAML registers its ReadingChanged event handler.

    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);
        }
    }
    

    The following example shows the ReadingChanged event handler.

    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);
        });
    }
    

    The following example demonstrates how a Windows Store app built with JavaScript registers its ReadingChanged event handler.

    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 following example shows the ReadingChanged event handler.

    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);
    }
    
  • Shaken
    Shaken
    Shaken
    Shaken

    Occurs when the accelerometer detects that the PC has been shaken.

    public event TypedEventHandler Shakenpublic event TypedEventHandler ShakenPublic Event Shaken

    Remarks

    Use this event to receive notification that the device containing the accelerometer has been shaken. The app is not required to set a report interval prior to registering for Shaken events.

    The following example demonstrates how a Windows Store app built with C# and XAML registers its Shaken event handler.

    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);
        }
    }
    

    The following example shows the Shaken event handler.

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

    The following example demonstrates how a Windows Store app built with JavaScript registers its Shaken event handler.

    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");
        }
    }
    

    The following example shows the Shaken event handler.

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

    Support for the Shaken event is dependent upon hardware and driver support. In practice, very few accelerometers support the Shaken event. If the accelerometer does not support the Shaken event and you add an event handler for the Shaken event, no error is raised, but the code in the event handler won’t run.

Attributes

Windows.Foundation.Metadata.ThreadingAttribute
Windows.Foundation.Metadata.StaticAttribute
Windows.Foundation.Metadata.MarshalingBehaviorAttribute
Windows.Foundation.Metadata.StaticAttribute
Windows.Foundation.Metadata.DualApiPartitionAttribute
Windows.Foundation.Metadata.ContractVersionAttribute

Details

Assembly

Windows.Devices.Sensors.dll