Quickstart: Responding to user movement with the accelerometer (VB)

You can use the accelerometer to respond to user movement in an app written in Visual Basic.

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 Basic, 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 Basic/Store Apps project types.

3. Replace the Visual Basic code

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

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

Imports Windows.Devices.Sensors
Imports Windows.UI.Core


''' <summary>
''' An empty page that can be used on its own or navigated to within a Frame.
''' </summary>
Public NotInheritable Class MainPage
    Inherits Page
    Private _accelerometer As Accelerometer
    Private _cd As CoreDispatcher

    Public Sub New()
        Me.InitializeComponent()

        _accelerometer = Accelerometer.GetDefault
        _cd = Window.Current.CoreWindow.Dispatcher

        If _accelerometer IsNot Nothing Then
            ' Set the report interval
            Dim minReportInterval As UInteger = _accelerometer.MinimumReportInterval
            Dim reportInterval As UInteger
            If minReportInterval > 16 Then
                reportInterval = minReportInterval
            Else
                reportInterval = 16
            End If
            _accelerometer.ReportInterval = reportInterval
            ' Set the event handler
            AddHandler _accelerometer.ReadingChanged, AddressOf ReadingChanged
        End If

    End Sub

    Private Async Sub ReadingChanged(ByVal sender As Object, ByVal e As AccelerometerReadingChangedEventArgs)
        Await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, Sub()
                                                                     Dim reading As AccelerometerReading = e.Reading
                                                                     txtX.Text = String.Format("{0,5:0.00}", reading.AccelerationX)
                                                                     txtY.Text = String.Format("{0,5:0.00}", reading.AccelerationY)
                                                                     txtZ.Text = String.Format("{0,5:0.00}", reading.AccelerationZ)
                                                                 End Sub)
    End Sub


End Class

4. Replace the XAML code

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

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

    <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
        <StackPanel>
            <TextBlock x:Name="txtX"  TextWrapping="Wrap" Text="No data" />
            <TextBlock x:Name="txtY"  TextWrapping="Wrap" Text="No data" />
            <TextBlock x:Name="txtZ"  TextWrapping="Wrap" Text="No data" />
        </StackPanel>
    </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 AccelerometerVB, you'd replace x:Class="App1.MainPage" with x:Class="AccelerometerVB.MainPage". You should also replace xmlns:local="using:App1" with xmlns:local="using:AccelerometerVB".

5. 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.

6. 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 New Sub.

_accelerometer = Accelerometer.GetDefault

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

 Dim minReportInterval As UInteger = _accelerometer.MinimumReportInterval
 Dim reportInterval As UInteger
 If minReportInterval > 16 Then
     reportInterval = minReportInterval
 Else
     reportInterval = 16
 End If
 _accelerometer.ReportInterval = reportInterval

The new accelerometer data is captured in the ReadingChanged Sub. 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.

AddHandler _accelerometer.ReadingChanged, AddressOf ReadingChanged
  

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

<TextBlock x:Name="txtX"  TextWrapping="Wrap" Text="No data" />
<TextBlock x:Name="txtY"  TextWrapping="Wrap" Text="No data" />
<TextBlock x:Name="txtZ"  TextWrapping="Wrap" Text="No data" />

Accelerometer class

Accelerometer Sample

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