다음을 통해 공유


자이로미터 사용하기

자이로미터를 사용하여 사용자 이동의 변화를 감지하는 방법을 알아봅니다.

중요 API

필수 조건

XAML(Extensible Application Markup Language), Microsoft Visual C#, 이벤트에 대해 잘 알고 있어야 합니다.

사용 중인 디바이스 또는 Emulator가 자이로미터를 지원해야 합니다.

간단한 자이로미터 앱 만들기

자이로미터는 가속도계를 게임 컨트롤러로 칭찬합니다. 가속도계는 선형 동작을 측정할 수 있으며 자이로미터는 각도 속도 또는 회전 동작을 측정합니다.

참고

더 완전한 구현은 회전계 샘플을 참조하세요.

지침

  • Visual C# 프로젝트 템플릿에서 빈 앱(Universal Windows)을 선택하여 새 프로젝트를 만듭니다.

  • 프로젝트의 MainPage.xaml.cs 파일을 열고 기존의 코드를 다음과 같이 바꿉니다.

    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 gyrometer


    namespace App1
    {
        /// <summary>
        /// An empty page that can be used on its own or navigated to within a Frame.
        /// </summary>
        public sealed partial class MainPage : Page
        {
            private Gyrometer _gyrometer; // Our app' s gyrometer object

            // This event handler writes the current gyrometer reading to
            // the three textblocks on the app' s main page.

            private async void ReadingChanged(object sender, GyrometerReadingChangedEventArgs e)
            {
                await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    GyrometerReading reading = e.Reading;
                    txtXAxis.Text = String.Format("{0,5:0.00}", reading.AngularVelocityX);
                    txtYAxis.Text = String.Format("{0,5:0.00}", reading.AngularVelocityY);
                    txtZAxis.Text = String.Format("{0,5:0.00}", reading.AngularVelocityZ);
                });
            }

            public MainPage()
            {
                this.InitializeComponent();
                _gyrometer = Gyrometer.GetDefault(); // Get the default gyrometer sensor object

                if (_gyrometer != null)
                {
                    // Establish the report interval for all scenarios
                    uint minReportInterval = _gyrometer.MinimumReportInterval;
                    uint reportInterval = minReportInterval > 16 ? minReportInterval : 16;
                    _gyrometer.ReportInterval = reportInterval;

                    // Assign an event handler for the gyrometer reading-changed event
                    _gyrometer.ReadingChanged += new TypedEventHandler<Gyrometer, GyrometerReadingChangedEventArgs>(ReadingChanged);
                }

            }
        }
    }

이전 코드 조각의 네임스페이스의 이름을 프로젝트에 지정한 이름으로 바꿔야 합니다. 예를 들어 GyrometerCS라는 프로젝트를 만든 경우, namespace App1을(를) namespace GyrometerCS(으)로 교체합니다.

  • MainPage.xaml 파일을 열고 이 파일의 원본 내용을 다음의 XAML로 바꿉니다.
        <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="#FF0C0C0C">
            <TextBlock HorizontalAlignment="Left" Height="23" Margin="8,8,0,0" TextWrapping="Wrap" Text="X-Axis:" VerticalAlignment="Top" Width="46" Foreground="#FFFDFDFD"/>
            <TextBlock x:Name="txtXAxis" HorizontalAlignment="Left" Height="23" Margin="67,8,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="88" Foreground="#FFFDFAFA"/>
            <TextBlock HorizontalAlignment="Left" Height="20" Margin="8,52,0,0" TextWrapping="Wrap" Text="Y Axis:" VerticalAlignment="Top" Width="46" Foreground="White"/>
            <TextBlock x:Name="txtYAxis" HorizontalAlignment="Left" Height="24" Margin="54,48,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="80" Foreground="#FFFBFBFB"/>
            <TextBlock HorizontalAlignment="Left" Height="21" Margin="8,93,0,0" TextWrapping="Wrap" Text="Z Axis:" VerticalAlignment="Top" Width="46" Foreground="#FFFEFBFB"/>
            <TextBlock x:Name="txtZAxis" HorizontalAlignment="Left" Height="21" Margin="54,93,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="63" Foreground="#FFF8F3F3"/>

        </Grid>
    </Page>

이전 코드 조각에서 클래스 이름의 첫 번째 부분을 앱의 네임스페이스로 바꿔야 합니다. 예를 들어 GyrometerCS라는 프로젝트를 만든 경우, x:Class="App1.MainPage"을(를) x:Class="GyrometerCS.MainPage"(으)로 교체합니다. 또한 xmlns:local="using:App1"을(를) xmlns:local="using:GyrometerCS"(으)로 대체해야 합니다.

  • F5 키를 누르거나 디버그>디버깅 시작을 선택하여 앱을 빌드하고 배포하고 실행합니다.

앱이 실행되면 자이로미터 값을 변경하기 위해 디바이스를 이동하거나 Emulator 도구를 사용할 수 있습니다.

  • Visual Studio로 돌아가서 Shift+F5를 눌러 앱을 중지하거나 디버그>디버깅 중지를 선택하여 앱을 중지합니다.

설명

이전 예시는 앱에서 자이로미터 입력을 통합하기 위해 작성해야 하는 코드가 얼마나 적은지를 보여 줍니다.

앱은 MainPage 메서드에서 기본 자이로미터와의 연결을 설정합니다.

_gyrometer = Gyrometer.GetDefault(); // Get the default gyrometer sensor object

앱은 MainPage 메서드 내에서 보고서 간격을 설정합니다. 이 코드는 디바이스에서 지원하는 최소 간격을 검색하고 요청된 간격인 16밀리초(약 60Hz 새로 고침 속도)와 비교합니다. 지원되는 최소 간격이 요청된 간격보다 큰 경우 코드는 값을 최소값으로 설정합니다. 그렇지 않으면 값을 요청된 간격으로 설정합니다.

uint minReportInterval = _gyrometer.MinimumReportInterval;
uint reportInterval = minReportInterval > 16 ? minReportInterval : 16;
_gyrometer.ReportInterval = reportInterval;

새로운 자이로미터 데이터는 ReadingChanged 메서드에서 캡처됩니다. 센서 드라이버가 센서에서 새 데이터를 받을 때마다 이 이벤트 처리기를 사용하여 값을 앱에 전달합니다. 앱은 다음의 줄에 이 이벤트 처리기를 등록합니다.

_gyrometer.ReadingChanged += new TypedEventHandler<Gyrometer,
GyrometerReadingChangedEventArgs>(ReadingChanged);

이러한 새 값은 프로젝트의 XAML에 있는 TextBlocks에 기록됩니다.

        <TextBlock HorizontalAlignment="Left" Height="23" Margin="8,8,0,0" TextWrapping="Wrap" Text="X-Axis:" VerticalAlignment="Top" Width="46" Foreground="#FFFDFDFD"/>
        <TextBlock x:Name="txtXAxis" HorizontalAlignment="Left" Height="23" Margin="67,8,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="88" Foreground="#FFFDFAFA"/>
        <TextBlock HorizontalAlignment="Left" Height="20" Margin="8,52,0,0" TextWrapping="Wrap" Text="Y Axis:" VerticalAlignment="Top" Width="46" Foreground="White"/>
        <TextBlock x:Name="txtYAxis" HorizontalAlignment="Left" Height="24" Margin="54,48,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="80" Foreground="#FFFBFBFB"/>
        <TextBlock HorizontalAlignment="Left" Height="21" Margin="8,93,0,0" TextWrapping="Wrap" Text="Z Axis:" VerticalAlignment="Top" Width="46" Foreground="#FFFEFBFB"/>
        <TextBlock x:Name="txtZAxis" HorizontalAlignment="Left" Height="21" Margin="54,93,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="63" Foreground="#FFF8F3F3"/>