por Cesar Cassiano Schimanco

Simular acelerômetro no Windows Phone 7 emulator + realidade aumentada

Para testar certos tipos de aplicativos, o Windows Phone 7 emulator é meio ou totalmente restrito, por falta de hardware. Por exemplo: câmera, GPS, 3G, sensores…
Então para testarmos o acelerômetro, podemos utilizar a webcam do notebook ou do PC com a ajuda da realidade aumentada, no caso o AccelKit, ferramenta que simula um sensor acelerômetro para Windows Phone 7.
 

Primeiro passo, entre em http://accelkit.codeplex.com e faça o download do AccelKit.
Agora descompacte e imprima o Print_This_Cutout.pdf, cole em um papelão ou outro material mais rígido, para que a folha não fique flexível e depois recorte.

Execute o accelKit.exe que esta na directório Executable, ai quando pedir para escolher a resolução você pode opatar pela mais baixa, para utilizar menus recursos de CPU. Procure estar em um local bem iluminado para que a imagem seja facilmente reconhecida.

Segundo passo, adicionar accelKit em nossa aplicação.
Nesse caso eu utilizei um exemplo pronto da Microsoft que testa o acelerômetro e alterei e adicionei o código complementar, no final desse artigo disponibilizo o projeto para download.

Crie um novo projeto, e em seguida adicione os arquivos AccelerometerEmu.cs e AccelerometerEmuReadingEventArgs.cs que estao no diretorio EmuClasses.

Abaixo vamos ver como fica o código.
 

MainPage.xaml

<phone:PhoneApplicationPage 
    x:Class="AccelerometerSample.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="PortraitOrLandscape" Orientation="Portrait"
    mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768"
    shell:SystemTray.IsVisible="True">

    <!--LayoutRoot contains the root grid where all other page content is placed-->
    <Grid x:Name="LayoutRoot" Background="Transparent">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <!--TitlePanel contains the name of the application and page title-->
        <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="24,24,0,12">
            <TextBlock x:Name="ApplicationTitle" Text="MY APPLICATION" Style="{StaticResource PhoneTextNormalStyle}"/>
            <TextBlock x:Name="PageTitle" Text="page name" Margin="-3,-8,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
        </StackPanel>

        <!--ContentPanel - place additional content here-->
        <Grid x:Name="ContentGrid" Grid.Row="1">
            <TextBlock VerticalAlignment="Top" Text="x:" Name="XLabel" Style="{StaticResource PhoneTextNormalStyle}" Margin="68,122,386,0" FontWeight="Bold"></TextBlock>
            <TextBlock VerticalAlignment="Top" Text=" " Name="XTextBlock" Style="{StaticResource PhoneTextExtraLargeStyle}" Margin="102,100,18,0" Foreground="{StaticResource PhoneAccentBrush}" FontWeight="Bold" FontFamily="Segoe WP Semibold"></TextBlock>
            <TextBlock VerticalAlignment="Top" Text="y:" Name="YLabel" Style="{StaticResource PhoneTextNormalStyle}" Margin="68,228,386,0" FontWeight="Bold"></TextBlock>
            <TextBlock VerticalAlignment="Top" Text=" " Name="YTextBlock" Style="{StaticResource PhoneTextExtraLargeStyle}" Margin="102,206,18,0" Foreground="{StaticResource PhoneAccentBrush}" FontWeight="Bold" FontFamily="Segoe WP Semibold"></TextBlock>
            <TextBlock VerticalAlignment="Top" Text="z:" Name="ZLabel" Style="{StaticResource PhoneTextNormalStyle}" Margin="68,330,386,0" FontWeight="Bold"></TextBlock>
            <TextBlock VerticalAlignment="Top" Text=" " Name="ZTextBlock" Style="{StaticResource PhoneTextExtraLargeStyle}" Margin="100,308,20,0"  Foreground="{StaticResource PhoneAccentBrush}" FontWeight="Bold" FontFamily="Segoe WP Semibold"></TextBlock>
            <TextBlock VerticalAlignment="Top" Text="status:" Name="statusLabel" Style="{StaticResource PhoneTextNormalStyle}" Margin="24,11,0,0" HorizontalAlignment="Left" Width="72" />
            <TextBlock VerticalAlignment="Top" Text="accelerometer stopped" Name="statusTextBlock" Style="{StaticResource PhoneTextNormalStyle}" Foreground="{StaticResource PhoneAccentBrush}" Margin="102,11,6,0" />
        </Grid>
    </Grid>
</phone:PhoneApplicationPage>


MainPage.xaml.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using NKast.Sensors;

namespace AccelerometerSample
{
    public partial class MainPage : PhoneApplicationPage
    {
        AccelerometerEmu accelerometer;

        #region Initialization
        public MainPage()
        {
            InitializeComponent();

            ApplicationBar = new ApplicationBar();
            ApplicationBar.IsVisible = true;

            ApplicationBarIconButton startStopButton = new ApplicationBarIconButton(new Uri("/Images/startstop.png", UriKind.Relative));
            startStopButton.Text = "on/off";
            startStopButton.Click += new EventHandler(startStopButton_Click);
            ApplicationBar.Buttons.Add(startStopButton);
        }

        #endregion

        #region User Interface
        void startStopButton_Click(object sender, EventArgs e)
        {
            if (accelerometer == null)
            {
                //Instanciando o objeto accelerometer
                accelerometer = new AccelerometerEmu();

                accelerometer.ReadingEmuChanged += new EventHandler<AccelerometerEmuReadingEventArgs>(accelerometer_ReadingChanged);

                statusTextBlock.Text = "starting accelerometer";
                accelerometer.Start();
            }
            else
            {
                accelerometer.Stop();
                accelerometer = null;
                statusTextBlock.Text = "accelerometer stopped";
            }
        }
        #endregion

        #region Accelerometer Event Handling
        void accelerometer_ReadingChanged(object sender, AccelerometerEmuReadingEventArgs e)
        {
            Deployment.Current.Dispatcher.BeginInvoke(() => MyReadingChanged(e));
        }
        
        void MyReadingChanged(AccelerometerEmuReadingEventArgs e)
        {
            statusTextBlock.Text = accelerometer.State.ToString();
            XTextBlock.Text = e.X.ToString("0.00");
            YTextBlock.Text = e.Y.ToString("0.00");
            ZTextBlock.Text = e.Z.ToString("0.00");
        }

        #endregion
    }
}

Download do projeto

Comentários

Carregando comentários

Postar um novo comentário



Processando...