Language: HTML | XAML

Quickstart: Responding to user movement with the accelerometer (C++)

You can use the accelerometer to respond to user movement in an app written in C++.

A simple game app relies on a single sensor, the accelerometer, as an input device. These apps typically use only one or two axes for input; but they may also use the shake event as another input source.

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 accelerometer to respond to user movement.

Prerequisites

You should be familiar with XAML, Visual C++, and events.

The device or emulator that you're using must support an accelerometer.

Time to complete: 20 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 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::Accelerometer^ sender, Windows::Devices::Sensors::AccelerometerReadingChangedEventArgs^ e);
        Windows::Devices::Sensors::Accelerometer^ accelerometer;
        Windows::Foundation::EventRegistrationToken listenerToken;

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

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 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 http://go.microsoft.com/fwlink/p/?linkid=234238

MainPage::MainPage()
{
    InitializeComponent();

    // Get the default accelerometer
    accelerometer = Accelerometer::GetDefault();

    // Setup the event handler
    if (accelerometer != nullptr)
    {
        // Establish the report interval for all scenarios
        uint32 minReportInterval = accelerometer->MinimumReportInterval;
        uint32 reportInterval = minReportInterval > 16 ? minReportInterval : 16;
        accelerometer->ReportInterval = reportInterval;

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

   
    }  
}

// The ReadingChanged event handler is invoked each time
// we receive a new reading from the driver.

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

                txtX->Text = reading->AccelerationX.ToString();
                txtY->Text = reading->AccelerationY.ToString();
                txtZ->Text = reading->AccelerationZ.ToString();
            },
            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 AccelerometerCS, you'd replace using namespace App1; with using namespace AccelerometerCPP;.

5. Replace the XAML code

Open the file MainPage.xaml and replace the original contents with the following XML.


<Page
    x:Class="App1.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:App1"
    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="White">
        <TextBlock HorizontalAlignment="Left" Height="20" Margin="0,8,0,0" TextWrapping="Wrap" Text="X:" VerticalAlignment="Top" Width="45" Foreground="#FF050404"/>
        <TextBlock x:Name="txtX" HorizontalAlignment="Left" Height="20" Margin="49,8,0,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top" Width="41" Foreground="#FF0C0C0C"/>
        <TextBlock HorizontalAlignment="Left" Height="22" Margin="0,28,0,0" TextWrapping="Wrap" Text="Y:" VerticalAlignment="Top" Width="45" Foreground="#FF090909"/>
        <TextBlock x:Name="txtY" HorizontalAlignment="Left" Height="22" Margin="49,28,0,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top" Width="41" Foreground="#FF0C0C0C"/>
        <TextBlock HorizontalAlignment="Left" Height="21" Margin="0,54,0,0" TextWrapping="Wrap" Text="Z:" VerticalAlignment="Top" Width="45" Foreground="#FF0C0C0C"/>
        <TextBlock x:Name="txtZ" HorizontalAlignment="Left" Height="21" Margin="49,54,0,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top" Width="41" Foreground="#FF070606"/>

    </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 AccelerometerCPP, you'd replace x:Class="App1.MainPage" with x:Class="AccelerometerCPP.MainPage". You should also replace xmlns:local="using:App1" with xmlns:local="using:AccelerometerCPP".

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 accelerometer input in your app.

The app establishes a connection with the default accelerometer in the MainPage method.


accelerometer = Accelerometer::GetDefault();

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


uint32 minReportInterval = accelerometer->MinimumReportInterval;
uint32 reportInterval = minReportInterval > 16 ? minReportInterval : 16;
 accelerometer->ReportInterval = reportInterval;


The new accelerometer 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 = accelerometer->ReadingChanged::add(ref new TypedEventHandler<Accelerometer^, 
                 AccelerometerReadingChangedEventArgs^>(this, &MainPage::ReadingChanged));


These new values are written to of the TextBlocks found in the project's XAML.


 <TextBlock HorizontalAlignment="Left" Height="20" Margin="0,8,0,0" TextWrapping="Wrap" Text="X:" VerticalAlignment="Top" Width="45" Foreground="#FF050404"/>
 <TextBlock x:Name="txtX" HorizontalAlignment="Left" Height="20" Margin="49,8,0,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top" Width="41" Foreground="#FF0C0C0C"/>
 <TextBlock HorizontalAlignment="Left" Height="22" Margin="0,28,0,0" TextWrapping="Wrap" Text="Y:" VerticalAlignment="Top" Width="45" Foreground="#FF090909"/>
 <TextBlock x:Name="txtY" HorizontalAlignment="Left" Height="22" Margin="49,28,0,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top" Width="41" Foreground="#FF0C0C0C"/>
 <TextBlock HorizontalAlignment="Left" Height="21" Margin="0,54,0,0" TextWrapping="Wrap" Text="Z:" VerticalAlignment="Top" Width="45" Foreground="#FF0C0C0C"/>
 <TextBlock x:Name="txtZ" HorizontalAlignment="Left" Height="21" Margin="49,54,0,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top" Width="41" Foreground="#FF070606"/>


Related topics

Accelerometer class
Accelerometer Sample
Roadmap for creating apps using C#, C++, or VB

 

 

Show:
© 2015 Microsoft