Get With Accelerometer in Your Windows Phone App

Introduction

Ironically, a single smartphone has as many sensors as a human body needs. A GPS Sensor, Proximity Sensor, Com, Accelerometer and Gyrsocpe are the popular ones that are used in Smartphones.

Every single sensor has their purpose to help the smartphone to make them smart enough.

Here, in this article we will only explain the Accelerometer.

Accelerometer

Background

An Accelerometer is a sensor device built in Windows Phone that measures the acceleration in three axes (X, Y, Z), relative to freefall. So, it is beneficial for a phone. Gaming is one of the major reasons to have this sensor in a phone.

So, we will have a small demonstration of an accelerometer.

demonstration accelerometer

Step 1: Start a new project that looks like:

new project

Step 2: Add "Microsoft.Devices.Sensor" in your references. So, you can include it in your project namespace. Ensure you have "using Microsoft.Devices.Sensor;".

Step 3: Then create an object of an Accelerometer in your class.

Accelerometer acc = new Accelerometer();

  //Suppose, I have 'acc'

Step 4: Now, create an Event that is raised when your Sensor becomes active. And you must code it inside the Constructor.

acc.ReadingChanged += new EventHandler<AccelerometerReadingEventArgs>(acc_ReadingChanged);

acc.Start();

Step 5: Now, it’s time to handle the Handler, in other words acc_RedaingChanged.

void acc_ReadingChanged(object sender, AccelerometerReadingEventArgs e)

{

    Deployment.Current.Dispatcher.BeginInvoke(() => ThreadSafeAccelerometerChanged(e));

}

void ThreadSafeAccelerometerChanged(AccelerometerReadingEventArgs e)

{

    X.Text = e.X.ToString("0.00");

    Y.Text = e.Y.ToString("0.00");

    Z.Text = e.Y.ToString("0.00");

}

Here, X.Text, Y.Text, Z.Text are the three TextBoxes what I have used in my Project. You can change that depending on your name.

Step 6: With its execution you get the postion of your Device. If you are using Emulator, then you have a special feature inside that.

Click on Special Option (>>) to get the Accelrometer.

get the Accelrometer

And now you can rotate your Emulator with that Orange Dot that is encircled with red in the right side. While rotating you can see all three of your Text Boxes change their value.

Text Box value

Conclusion

You can use this incredible feature in your app. Generally, these are used in your game or "ShakeMe" app. If you encounter any issue then try it with the enclosed source code.


Similar Articles