Compass Compass Compass Compass Class

Represents a compass sensor.

This sensor returns a heading with respect to True North and, possibly, Magnetic North. (The latter is dependent on the sensor capabilities.)

Syntax

Declaration

public sealed class Compasspublic sealed class CompassPublic NotInheritable Class Compasspublic sealed class Compass

Remarks

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() method to establish a connection to a compass. If no integrated compass is found, the method will return a null value.

_compass = Compass.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 (_compass != null)
    {
        // Establish the report interval
        _compass.ReportInterval = _desiredReportInterval;

        Window.Current.VisibilityChanged += new WindowVisibilityChangedEventHandler(VisibilityChanged);
        _compass.ReadingChanged += new TypedEventHandler<Compass, CompassReadingChangedEventArgs>(ReadingChanged);

        ScenarioEnableButton.IsEnabled = false;
        ScenarioDisableButton.IsEnabled = true;
    }
    else
    {
        rootPage.NotifyUser("No compass found", NotifyType.StatusMessage);
    }
}

The following example shows the ReadingChanged event handler.

async private void ReadingChanged(object sender, CompassReadingChangedEventArgs e)
{
    await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
    {
        CompassReading reading = e.Reading;
        ScenarioOutput_MagneticNorth.Text = String.Format("{0,5:0.00}", reading.HeadingMagneticNorth);
        if (reading.HeadingTrueNorth != null)
        {
            ScenarioOutput_TrueNorth.Text = String.Format("{0,5:0.00}", reading.HeadingTrueNorth);
        }
        else
        {
            ScenarioOutput_TrueNorth.Text = "No data";
        }
    });
}

Properties summary

Gets the device identifier.

Gets the minimum report interval supported by the compass.

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 or sets the current report interval for the compass.

Methods summary

Gets the current compass reading.

Returns the default compass.

Events summary

Occurs each time the compass reports a new sensor reading.

Properties

  • DeviceId
    DeviceId
    DeviceId
    DeviceId

    Gets the device identifier.

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

    Property Value

    • string
      string
      string
      string

      The device identifier.

  • MinimumReportInterval
    MinimumReportInterval
    MinimumReportInterval
    MinimumReportInterval

    Gets the minimum report interval supported by the compass.

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

    Property Value

    • uint
      uint
      uint
      uint

      The minimum ReportInterval supported by the sensor.

    Remarks

    The interval is specified in milliseconds.

  • 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 DisplayOrientationspublic DisplayOrientations ReadingTransform { get; set; }

    Property Value

  • ReportInterval
    ReportInterval
    ReportInterval
    ReportInterval

    Gets or sets the current report interval for the compass.

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

    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.

    The Sensor platform automatically sets the change sensitivity for compasses based on the current report interval. This table specifies the change sensitivity values for given intervals.

    Current report interval (specified in milliseconds)Change sensitivity (specified in degrees)
    1 ms – 16 ms0.01 degrees
    17 ms – 32 ms0.5 degrees
    >= 33 ms2 degrees

Methods

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

    Gets the current compass reading.

    public CompassReading GetCurrentReading()public CompassReading GetCurrentReading()Public Function GetCurrentReading() As CompassReadingpublic CompassReading GetCurrentReading()

    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

    The returned value is a magnetic heading specified in degrees.

    The accuracy of this value is dependent on the capabilities of the compass.

    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 heading for the default compass.

    private void DisplayCurrentReading(object sender, object args)
    {
        CompassReading reading = _compass.GetCurrentReading();
        if (reading != null)
        {
            ScenarioOutput_MagneticNorth.Text = String.Format("{0,5:0.00}", reading.HeadingMagneticNorth);
            if (reading.HeadingTrueNorth != null)
            {
                ScenarioOutput_TrueNorth.Text = String.Format("{0,5:0.00}", reading.HeadingTrueNorth);
            }
            else
            {
                ScenarioOutput_TrueNorth.Text = "No data";
            }
        }
    }
    

    The following example demonstrates how a Windows Store app built for Windows using JavaScript retrieves the current heading for the default compass.

    function getCurrentReading() {
        var reading = compass.getCurrentReading();
        if (reading) {
            document.getElementById("readingOutputMagneticNorth").innerHTML = reading.headingMagneticNorth.toFixed(2);
            if (reading.headingTrueNorth) {
                document.getElementById("readingOutputTrueNorth").innerHTML = reading.headingTrueNorth.toFixed(2);
            } else {
                document.getElementById("readingOutputTrueNorth").innerHTML = "no data";
            }
        }
    }
    
  • GetDefault()
    GetDefault()
    GetDefault()
    GetDefault()

    Returns the default compass.

    public static Compass GetDefault()public static Compass GetDefault()Public Static Function GetDefault() As Compasspublic static Compass GetDefault()

    Returns

    Remarks

    This method only returns values for a compass 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() 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 compass.

    _compass = Compass.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 compass.

    compass = Windows.Devices.Sensors.Compass.getDefault();
    

Events

  • ReadingChanged
    ReadingChanged
    ReadingChanged
    ReadingChanged

    Occurs each time the compass reports a new sensor reading.

    public event TypedEventHandler ReadingChangedpublic event TypedEventHandler ReadingChangedPublic Event ReadingChangedpublic event TypedEventHandler 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.

    Applications can set the frequency of this event by setting the ReportInterval property.

    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 (_compass != null)
        {
            // Establish the report interval
            _compass.ReportInterval = _desiredReportInterval;
    
            Window.Current.VisibilityChanged += new WindowVisibilityChangedEventHandler(VisibilityChanged);
            _compass.ReadingChanged += new TypedEventHandler<Compass, CompassReadingChangedEventArgs>(ReadingChanged);
    
            ScenarioEnableButton.IsEnabled = false;
            ScenarioDisableButton.IsEnabled = true;
        }
        else
        {
            rootPage.NotifyUser("No compass found", NotifyType.StatusMessage);
        }
    }
    

    The following example shows the ReadingChanged event handler.

    async private void ReadingChanged(object sender, CompassReadingChangedEventArgs e)
    {
        await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
        {
            CompassReading reading = e.Reading;
            ScenarioOutput_MagneticNorth.Text = String.Format("{0,5:0.00}", reading.HeadingMagneticNorth);
            if (reading.HeadingTrueNorth != null)
            {
                ScenarioOutput_TrueNorth.Text = String.Format("{0,5:0.00}", reading.HeadingTrueNorth);
            }
            else
            {
                ScenarioOutput_TrueNorth.Text = "No data";
            }
        });
    }
    

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

    function enableReadingChangedScenario() {
        if (compass) {
            // Set the reportInterval to enable the sensor events
            compass.reportInterval = reportInterval;
    
            document.addEventListener("msvisibilitychange", msVisibilityChangeHandler, false);
            compass.addEventListener("readingchanged", onDataChanged);
            document.getElementById("scenario1Open").disabled = true;
            document.getElementById("scenario1Revoke").disabled = false;
        } else {
            WinJS.log && WinJS.log("No compass found", "sample", "error");
        }
    }
    

    The following example shows the ReadingChanged event handler.

    function onDataChanged(e) {
        var reading = e.reading;
    
        document.getElementById("eventOutputMagneticNorth").innerHTML = reading.headingMagneticNorth.toFixed(2);
        if (reading.headingTrueNorth) {
            document.getElementById("eventOutputTrueNorth").innerHTML = reading.headingTrueNorth.toFixed(2);
        }
    }
    

Device family

Windows 10 (introduced v10.0.10240.0)

API contract

Windows.Foundation.UniversalApiContract (introduced v1)

Attributes

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

Details

Assembly

Windows.Devices.Sensors.dll