Quickstart: Determining current heading with the compass (C#)
You can use the compass to determine the current heading with an app written in C#.
An app can retrieve the current heading with respect to magnetic, or true, north.
Navigation apps use the compass to determine the direction a device is facing and then orient the map accordingly.
Roadmap: How does this topic relate to others? See: Roadmap for Windows Store apps using C# or Visual Basic.
Objective: After completing this quickstart you will understand how to use the compass to detect changes in movement.
Prerequisites
You should be familiar with XAML, Visual C#, and events.
The device that you're using must have a compass.
Time to complete: 20 minutes.
Instructions
1. Open Microsoft Visual Studio Express 2012 for Windows 8
Open an instance of Microsoft Visual Studio Express 2012 for Windows 8.
2. Create a new project
Create a new project, choosing a Blank Application from the Visual C#/Windows Store project types.
3. Insert the app C#
Open your project's BlankPage.xaml.cs file and replace the existing code with the following.
using System; using System.Collections.Generic; using System.IO; using System.Linq; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; using Windows.UI.Core; // Required to access the core dispatcher object using Windows.Devices.Sensors; // Required to access the sensor platform and the compass // The Blank Page item template is documented at http://go.microsoft.com/fwlink/p/?linkid=234238 namespace Application1 { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class BlankPage : Page //partial class MainPage { private Compass _compass; // Our app's compass object // This event handler writes the current compass reading to // the textblocks on the app's main page. private void ReadingChanged(object sender, CompassReadingChangedEventArgs e) { Dispatcher.RunAsync(CoreDispatcherPriority.Normal, (s, a) => { CompassReading reading = (a.Context as CompassReadingChangedEventArgs).Reading; txtMagnetic.Text = String.Format("{0,5:0.00}", reading.HeadingMagneticNorth); if (reading.HeadingTrueNorth.HasValue) txtNorth.Text = String.Format("{0,5:0.00}", reading.HeadingTrueNorth); else txtNorth.Text = "No reading."; }, this, e); } public BlankPage() { InitializeComponent(); _compass = Compass.GetDefault(); // Get the default compass object // Assign an event handler for the compass reading-changed event if (_compass != null) { // Establish the report interval for all scenarios uint minReportInterval = _compass.MinimumReportInterval; uint reportInterval = minReportInterval > 16 ? minReportInterval : 16; _compass.ReportInterval = reportInterval; _compass.ReadingChanged += new TypedEventHandler<Compass, CompassReadingChangedEventArgs>(ReadingChanged); } } } }
You'll need to replace the class name in the previous snippet with the name of your app's class. For example, if you created a project named "Application2", you'd replace the following.
namespace Application1
You'd replace it with the following.
namespace Application2
4. Insert the app XAML
Open the file BlankPage.xaml and copy the following XML into this file (replacing its original contents).
<Page x:Class="Application1.BlankPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:Application1" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d"> <Grid x:Name="LayoutRoot" Background="#FF0C0C0C"> <TextBlock HorizontalAlignment="Left" Height="22" Margin="8,18,0,0" TextWrapping="Wrap" Text="Magnetic Heading:" VerticalAlignment="Top" Width="104" Foreground="#FFFBF9F9"/> <TextBlock HorizontalAlignment="Left" Height="18" Margin="8,58,0,0" TextWrapping="Wrap" Text="True North Heading:" VerticalAlignment="Top" Width="104" Foreground="#FFF3F3F3"/> <TextBlock x:Name="txtMagnetic" HorizontalAlignment="Left" Height="22" Margin="130,18,0,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top" Width="116" Foreground="#FFFBF6F6"/> <TextBlock x:Name="txtNorth" HorizontalAlignment="Left" Height="18" Margin="130,58,0,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top" Width="116" Foreground="#FFF5F1F1"/> </Grid> </Page>
You'll need to replace the first part of the class name in the previous snippet with the name of your app's class. For example, if you created a project named "Application2", you'd replace the following.
x:Class="Application1.BlankPage"
You'd replace it with the following.
x:Class="Application2.BlankPage"
5. Build the app
Choose Build > Build Solution to build the project.
6. Deploy the app
Choose Build > Deploy Solution to deploy the app.
7. Run the app
- Close Visual Studio Express 2012 for Windows 8.
- Start the App Launcher.
- Locate your app from the list of available apps and choose Launch.
Summary
The previous example demonstrates how little code you'll need to write in order to integrate compass input in your app.
The app establishes a connection with the default compass in the BlankPage method. This occurs on the following line.
_compass = Compass.GetDefault(); // Get the default compass object
The app establishes the report interval within the BlankPage method. This code retrieves the minimum interval supported by the device and compares it to a requested interval of 16 milliseconds (which approximates a 60-Hz refresh rate). If the minimum supported interval is greater than the requested interval, the code sets the value to the minimum. Otherwise, it sets the value to the requested interval.
uint minReportInterval = _accelerometer.MinimumReportInterval; uint reportInterval = minReportInterval > 16 ? minReportInterval : 16; _accelerometer.ReportInterval = reportInterval;
The new compass data is captured in the ReadingChanged method. Each time the sensor driver receives new data from the sensor, it passes the values to your app using this function (or event handler). The app registers this event handler on the following line.
_compass.ReadingChanged += new TypedEventHandler<Compass,
CompassReadingChangedEventArgs>(ReadingChanged);
These new values are written to the two TextBlocks found in the project's XAML.
<TextBlock HorizontalAlignment="Left" Height="22" Margin="8,18,0,0" TextWrapping="Wrap" Text="Magnetic Heading:" VerticalAlignment="Top" Width="104" Foreground="#FFFBF9F9"/> <TextBlock HorizontalAlignment="Left" Height="18" Margin="8,58,0,0" TextWrapping="Wrap" Text="True North Heading:" VerticalAlignment="Top" Width="104" Foreground="#FFF3F3F3"/> <TextBlock x:Name="txtMagnetic" HorizontalAlignment="Left" Height="22" Margin="130,18,0,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top" Width="116" Foreground="#FFFBF6F6"/> <TextBlock x:Name="txtNorth" HorizontalAlignment="Left" Height="18" Margin="130,58,0,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top" Width="116" Foreground="#FFF5F1F1"/>
Related topics
Build date: 10/26/2012