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.
Let’s see the steps:
- Create a new Windows 10 universal app.
- Design the UI according to your wish; here I have created one button to start the Compass reading.
- Now go to the coding part and write the following code. Firstly, add the following namespace to access the compass sensor API.
- using Windows.Devices.Sensors;
- Create one object for the compass,
- Now get the default properties and reading by using GetDefault method.
- myCompass = Compass.GetDefault();
- Then set interval to read the value from certain interval.
- myCompass.ReportInterval = 16;
Now create one event compass reading changes to handle the readings and assign it to your compass.
- 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:
- public async void StartReadingCompass()
- {
- myCompass = Compass.GetDefault();
- uint interval = myCompass.MinimumReportInterval;
- uintreportinterval = interval > 16 ? interval : 16;
- myCompass.ReportInterval = reportinterval;
- myCompass.ReadingChanged += MyCompass_ReadingChanged;
- }
- private void MyCompass_ReadingChanged(Compass sender, CompassReadingChangedEventArgsargs)
- {
- CompassReading readings = args.Reading;
- stringnorthDirecction = String.Format("{0,5:0.00}", readings.HeadingTrueNorth);
- stringnorthMagnetic = String.Format("{0,5:0.00}", readings.HeadingMagneticNorth);
- }
Read more articles on Universal Windows Apps: