Partager via


Quickstart: Determining current heading with the compass (C++)

You can use the compass to determine the current heading with an app written in C++. And, your 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 Runtime 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 or emulator that you're using must support an compass.

Time to complete: 25 minutes.

Instructions

1. Open Microsoft Visual Studio

Open an instance of Microsoft Visual Studio.

2. Create a new project

Create a new project, choosing a Blank App from the Visual C++/Store Apps project types.

3. Replace the header file contents

Open your project's MainPage.xaml.h file and replace the existing comments, code, and definitions with the following.

//
// MainPage.xaml.h
// Declaration of the MainPage.xaml class.
//

#pragma once


#include "MainPage.g.h"

namespace App1
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public ref class MainPage sealed
    {
    public:
        MainPage();

    private:
        void ReadingChanged(Windows::Devices::Sensors::Compass^ sender, Windows::Devices::Sensors::CompassReadingChangedEventArgs^ e);

        Windows::Devices::Sensors::Compass^ compass;
        Windows::Foundation::EventRegistrationToken listenerToken;
        Windows::UI::Xaml::DispatcherTimer^ dispatcherTimer;

    protected:
        virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
    };
}

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 CompassCPP, you'd replace namespace App1 with namespace CompassCPP.

4. Replace the C++ code

Open your project's MainPage.xaml.cpp file and replace the existing code with the following.

//
// MainPage.xaml.cpp
// Implementation of the MainPage.xaml class.
//

#include "pch.h"
#include "MainPage.xaml.h"

using namespace App1;

using namespace Platform;
using namespace Windows::Foundation;
using namespace Windows::Foundation::Collections;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Controls::Primitives;
using namespace Windows::UI::Xaml::Data;
using namespace Windows::UI::Xaml::Input;
using namespace Windows::UI::Xaml::Media;
using namespace Windows::UI::Xaml::Navigation;

// Below namespaces are required to support sensors and events
using namespace Windows::System;
using namespace Windows::Foundation;
using namespace Platform;
using namespace Windows::Devices::Sensors;
using namespace Windows::UI::Core;

// The Blank Page item template is documented at https://go.microsoft.com/fwlink/p/?linkid=234238

MainPage::MainPage()
{
    InitializeComponent();

    compass = Compass::GetDefault();
    if (compass != nullptr)
    {
        // Establish the report interval for all scenarios
        uint32 minReportInterval = compass->MinimumReportInterval;
        uint32 reportInterval = minReportInterval > 16 ? minReportInterval : 16;
        compass->ReportInterval = reportInterval;

        // Establish the event handler
        listenerToken = compass->ReadingChanged::add(ref new TypedEventHandler<Compass^, CompassReadingChangedEventArgs^>(this, &MainPage::ReadingChanged));

    }
}

void MainPage::ReadingChanged(Compass^ /* sender */, CompassReadingChangedEventArgs^ e)
{
    auto ignored = Dispatcher->RunAsync(
        CoreDispatcherPriority::Normal,
        ref new DispatchedHandler(
            [this, e]()
            {
                CompassReading^ reading = e->Reading;

                txtMagnetic->Text = reading->HeadingMagneticNorth.ToString();
                if (reading->HeadingTrueNorth != nullptr)
                {
                    txtNorth->Text = reading->HeadingTrueNorth->Value.ToString();
                }
                else
                {
                    txtNorth->Text = "No data";
                }
            },
            CallbackContext::Any
            )
        );
}

/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached.  The Parameter
/// property is typically used to configure the page.</param>
void MainPage::OnNavigatedTo(NavigationEventArgs^ e)
{
}

You'll need to rename the namespace in the previous snippet with the name you gave your project. For example, if you created a project named CompassCS, you'd replace using namespace App1; with using namespace CompassCPP;.

5. Replace the XAML code

Open the file MainPage.xaml and copy the following XML into this file (replacing its original contents).

<Page
    x:Class="CompassCPP.MainPage"
    xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:CompassCPP"
    xmlns:d="https://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="https://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Grid Background="{StaticResource ApplicationPageBackgroundBrush}">
        <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 namespace of your app. For example, if you created a project named CompassCPP, you'd replace x:Class="App1.MainPage" with x:Class="CompassCPP.MainPage". You should also replace xmlns:local="using:App1" with xmlns:local="using:CompassCPP".

6. Build, deploy and run the app

Press F5 or select Debug > Start Debugging to build, deploy, and run the app.

Once the app is running, you can change the accelerometer values by moving the device or using the emulator tools.

7. Stop the app

  1. Press ALT+Tab to return to Visual Studio.
  2. Press Shift+F5 or select Debug > Stop Debugging to stop the app.

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 MainPage constructor.

compass = Compass::GetDefault();

The app also establishes the report interval within the MainPage constructor. 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.

 uint32 minReportInterval = compass->MinimumReportInterval;
 uint32 reportInterval = minReportInterval > 16 ? minReportInterval : 16;
 compass->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 event handler. The app registers this event handler on the following line.

listenerToken = compass->ReadingChanged::add(ref new TypedEventHandler<Compass^, 
CompassReadingChangedEventArgs^>(this, &MainPage::ReadingChanged));

These new values are written to the 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"/>

Compass class

Compass Sample

Roadmap for creating apps using C#, C++, or VB