Use Compass Sensor In Windows 10 Universal App

In Windows 10 the compass sensor is used to detect the Earth’s magnetic field in a particular interval or default.

It provides mobile phones with a simple orientation in relation to the Earth's magnetic field.

Look at the following image to get a clear idea about Earth’s magnetic field direction changes and how it works to identify the device direction.

compass

Let’s see the steps:

  1. Create a new Windows 10 universal app.

  2. Design the UI according to your wish; here I have created one button to start the Compass reading.

  3. Now go to the coding part and write the following code. Firstly, add the following namespace to access the compass sensor API.
    1. using Windows.Devices.Sensors;  
  4. Create one object for the compass,
    1. CompassmyCompass;;  
  5. Now get the default properties and reading by using GetDefault method.
    1. myCompass = Compass.GetDefault();  
  6. Then set interval to read the value from certain interval.
    1. myCompass.ReportInterval = 16;  

Now create one event compass reading changes to handle the readings and assign it to your compass.

  1. myCompass.ReadingChanged += MyCompass_ReadingChanged;  
Now start the application and get the values from the compass.

To read the compass value use CompassReadingclass.

Here's the complete code:
  1. public async void StartReadingCompass()  
  2. {  
  3.     myCompass = Compass.GetDefault();  
  4.     uint interval = myCompass.MinimumReportInterval;  
  5.     uintreportinterval = interval > 16 ? interval : 16;  
  6.     myCompass.ReportInterval = reportinterval;  
  7.     myCompass.ReadingChanged += MyCompass_ReadingChanged;  
  8. }  
  9. private void MyCompass_ReadingChanged(Compass sender, CompassReadingChangedEventArgsargs)  
  10. {  
  11.     CompassReading readings = args.Reading;  
  12.     stringnorthDirecction = String.Format("{0,5:0.00}", readings.HeadingTrueNorth); //Gets the heading in degrees relative to geographic true - north.  
  13.     stringnorthMagnetic = String.Format("{0,5:0.00}", readings.HeadingMagneticNorth); //Gets the heading in degrees relative to magnetic-north.  
  14. }  
Read more articles on Universal Windows Apps: