Windows Phone 7 (Mango) Tutorial - 21 - Small Demo of Accelerometer Application



Last two days we learned about Accelerometer class, it's base class and the accelerometer tool that comes with the Phone emulator. Hope those posts gave you some basic idea about it.

 

Here in this post, we will learn the use of this feature with a small demo application. We will also learn how to use the phone to write application that depends on the gravitational force applied to the sensors. This will give you better idea to create game application that will work when the user moves his phone device.

 

Index - Windows Phone 7 (Mango) Tutorial

 

Create the XAML Page

We need to create the UI of our small demo application. To do this, open the MainPage.xaml file and add the following Lines inside the ContentPanel. Those will create three different lines in three different axis. xLine is a Red line placed in the X-Axis, similarly yLine and zLine are Green and Blue coloured lines present in the Y and Z axis respectively.

 

WP7.1 Demo - Accelerometer - Line control XAML

 

You can add the following lines of xaml code to the content too. These TextBlocks will allow you to show the (x,y,z) coordinates of the current position where main gravity has been applied.

 

In the code behind we will create three Dependency Properties named XValue, YValue, ZValue and bind them to those textblocks respectively. These properties will return the current position where the centralized gravitational force has been applied to the device. Have a look into the code below:

 

WP7.1 Demo - Accelerometer - Line Value XAML

 

For your reference, sharing the complete XAML code here:

 
<!--ContentPanel - place additional content here-->
<StackPanel x:Name="ContentPanel" Grid.Row="1"
            Margin="12,0,12,0" Orientation="Vertical">
    <Grid Margin="0,0,0,50">                
        <Line x:Name="xLine" X1="220" Y1="200" X2="320" Y2="200" 
              Stroke="Red" StrokeThickness="5"/>
        <Line x:Name="yLine" X1="220" Y1="200" X2="220" Y2="110" 
              Stroke="Green" StrokeThickness="5"/>
        <Line x:Name="zLine" X1="220" Y1="200" X2="170" Y2="250" 
              Stroke="Blue" StrokeThickness="5"/>
    </Grid>
 
    <TextBlock Name="xValue" 
               Text="{Binding XValue, ElementName=phonePage, StringFormat='X: {0}'}" 
               Foreground="Red" HorizontalAlignment="Center"/>
    <TextBlock Name="yValue" 
               Text="{Binding YValue, ElementName=phonePage, StringFormat='Y: {0}'}" 
               Foreground="Green" HorizontalAlignment="Center"/>
    <TextBlock Name="zValue" 
               Text="{Binding ZValue, ElementName=phonePage, StringFormat='Z: {0}'}" 
               Foreground="Blue" HorizontalAlignment="Center"/>            
</StackPanel>

 

Create Accelerometer Instance

Now once the UI is ready, it's time to create the instance of the Accelerometer. Open the code behind file and inside the constructor first check whether your device supports accelerometer. If not show a message or do something depending on your requirement. Else, create the instance of the Accelerometer class and register the CurrentValueChanged event to it. Finally call the Start() method to instantiate the same.

 

WP7.1 Demo - Accelerometer - Create Instance

 

Updating the UI on Acceleration

Now when you move your device, you need to update the UI and show the X, Y and Z axis lines based on the position of the device. To do this implement the accelerometer's CurrentValueChanged event which takes object and SensorReadingEventArg<AccelerometerReading> as the parameter. SensorReadingEventArgs returns the current value of the accelerated value.

 

Give a call to UpdateUI() method and send the SensorReading value to it. The UpdateUI() method implementation will look as below:

 

WP7.1 Demo - Accelerometer - Update the UI based on Current Value Change

 

You can see that, from the accelerometer reading we are getting the Acceleration as Vector3 object which returns the X, Y and Z coordinates value. Based on them, set the position of the lines to the UI. This will show up the lines in proper axis.

 

Remember that, it is just a sample demo where we showcasing the feature. You need to implement your proper logic based on your requirement.

 

See it in Action

Let's see how it effects in the application. Run the application inside your phone emulator. You will see a single line in the screen as shown below. Now open the Accelerometer tool as discussed in the previous chapter. In the tools window, you will see the circle present at the middle of the phone which means the gravitational force applied to the central location of the device.

 

WP7.1 Demo - Accelerometer - UI     WP7.1 Demo - Accelerometer Tool

 

Drag it to a different position and you will notice that the phone is also changing it's position in 3D space. That means, you are actually moving your hardware device in different angle. In the emulator, you will notice that the X, Y and Z coordinate values are also changing and in different angle you will see different lines in different coordinate axis. At some point of time you will see all the three lines as shown below:

 

WP7.1 Demo - Accelerometer Tool - Placing the Phone in Emulator     WP7.1 Demo - Accelorometer Demo

 

Hope like other chapters this post was also helpful to you to understand the feature. If you still have any queries, drop a line here. I will try to help you as soon as possible. Stay in touch for the coming new posts on the tutorial series.

 

Don't forget to follow my tweets @kunal2383. I also have my blog page hosted on facebook. Feel free to like my facebook page to stay in touch with latest article news. Happy coding.

10 comments

  1. Hey Now Kunal Chowdhury;

    Great post & Mango info!

    Thx 4 the info;
    Catto

    ReplyDelete
  2. Hi
    This looks very useful but as VB person it is harder to follow.

    Is the source for all these projects available for download?

    Thanks

    Victor

    ReplyDelete
  3. Hi Victor,

    If you follow the steps properly, explained in my articles, you will be able to create them very easily. Let me know, if you need further help.

    Regards,
    Kunal

    ReplyDelete
  4. hello,

    I seem to have a problem with only 1 line of code , i'm new to programming and wanted to know if anyone can assist me.

    I get a compiler error with the following line:

    Dispatcher.BeginInvoke(() => UpdateUI(e.SensorReading));

    error message: "An object reference is required for the non-static field method or property 'system.windows.treading.dispatcher.begininvoke(systen.action)".

    I added using System.Windows.Threading in attempt to fix the problem but failed to succeed.

    Please any help is welcome. As i said im fairly new to programming , so bare with me.

    Frik.

    ReplyDelete
  5. Hi Frik,
    Looks like your UpdateUI() method is getting some null object. Debug the method, you will definitely find the issue.

    ReplyDelete
  6. Hello,

    Thank you for your fast reply, I found and fixed the problem. Thanx for the help and the wonderfull piece of code.

    Frik.

    ReplyDelete
  7. Glad to hear that, you found the issue.

    ReplyDelete
  8. There's no Vector3 object in my project, which library should I include to have it !?

    ReplyDelete
  9. @Anonymous, make sure that, you installed Windows phone 7.1 SDK and using Windows Phone 7.1 project template.

    ReplyDelete
  10. Thank you for a very useful article!

    @Anonymous add the statement using Microsoft.Xna.Framework to your file. But also remember to actually add that reference by right-clicking on References in the Solution Explorer.

    ReplyDelete


 
© 2008-2014 Kunal-Chowdhury.com | Designed by Kunal Chowdhury
Back to top