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,
- CompassmyCompass;;
- 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;
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); //Gets the heading in degrees relative to geographic true - north.
- stringnorthMagnetic = String.Format("{0,5:0.00}", readings.HeadingMagneticNorth); //Gets the heading in degrees relative to magnetic-north.
- }


Andrew CooperPosted Apr 11, 2016, 6:53 PM EDT
This works great most the time, though randommly Compass.GetDefault(); = null. Any ideas?
Suresh MPosted Feb 28, 2016, 6:18 PM EST
thank you friends
Asfend YarPosted Feb 26, 2016, 10:19 AM EST
Suresh M ... I've a problem actually I want to develop a compass in uwp. Can you ellaborate what can I do for needle rotation and movement
Midhun Jo AntonyPosted Feb 20, 2016, 5:18 AM EST
useful information...nicely said
Santhakumar MunuswamyPosted Feb 19, 2016, 9:37 PM EST
Thanks for nice share
Sibeesh VenuTOP 100Posted Feb 19, 2016, 8:38 PM EST
Nice Share
Debasis SahaTOP 100Posted Feb 19, 2016, 8:05 PM EST
Good One..
Ehsan SajjadPosted Feb 19, 2016, 10:38 AM EST
brief and informative
Mohammed IbrahimPosted Feb 19, 2016, 9:46 AM EST
nice
Asfend YarPosted Feb 19, 2016, 7:13 AM EST
Love you brother !!! You're such a valuable person on c-sharp corner ...Thanks a lot
Shubham KumarPosted Feb 19, 2016, 2:39 AM EST
nice