Overview
The Compass sensor provides access to the magnetic field sensor on a device. This sensor can be used to determine the device's orientation relative to the Earth's magnetic field. The Compass sensor is a core component of UWP applications that require orientation detection.
Properties
The Compass Sensor exposes several properties for configuration and status monitoring.
- Heading: (double-precision float) Represents the device's heading in degrees (0-359).
- Pitch: (double-precision float) Represents the device's pitch angle in degrees (-90 to 90).
- Roll: (double-precision float) Represents the device's roll angle in degrees (-90 to 90).
- IsSamplingRequested: (bool) Indicates whether the sensor is currently sampling.
Methods
The Compass Sensor provides methods for starting and stopping sampling, and for configuring the sample rate.
- StartSampling(): Starts sampling from the sensor.
- StopSampling(): Stops sampling from the sensor.
- SetSampleRate(TimeSpan frequency): Configures the sampling frequency.
Code Samples
Here are a few example code snippets demonstrating the usage of the Compass Sensor.
Example 1: Getting the Heading
// Assuming you have a CompassSensor object named compassSensor
if (compassSensor != null && compassSensor.IsSamplingRequested == false)
{
compassSensor.StartSampling();
while (compassSensor.IsSamplingRequested)
{
double heading = compassSensor.Heading;
Console.WriteLine("Heading: " + heading);
}
compassSensor.StopSampling();
}