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, 10:53 PM
This works great most the time, though randommly Compass.GetDefault(); = null. Any ideas?
Suresh MPosted Feb 28, 2016, 11:18 PM
thank you friends
Asfend YarPosted Feb 26, 2016, 3:19 PM
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, 10:18 AM
useful information...nicely said
Santhakumar MunuswamyPosted Feb 20, 2016, 2:37 AM
Thanks for nice share
Sibeesh VenuPosted Feb 20, 2016, 1:38 AM
Nice Share
Debasis SahaPosted Feb 20, 2016, 1:05 AM
Good One..
Ehsan SajjadPosted Feb 19, 2016, 3:38 PM
brief and informative
Mohammed IbrahimPosted Feb 19, 2016, 2:46 PM
nice
Asfend YarPosted Feb 19, 2016, 12:13 PM
Love you brother !!! You're such a valuable person on c-sharp corner ...Thanks a lot
Shubham KumarPosted Feb 19, 2016, 7:39 AM
nice