In this post we will see how to read different axis values using the Accelerometer
API.
To work with the Accelerometer API, first you need to add reference of
Microsoft.Devices.Sensors
Then the below namespace,
Now to capture X Axis, Y Axis and Z Axis value you need to follow the below steps
Step 1
Create a task object of Accelerometer chooser
Step 2
Call the callback method when the user will complete a task and Implement the
completed event to capture user data and status when user complete as tasks.
Step 3
Call the start method to start the accelerometer,
Step 4
We can read the values of XAxis, YAxis and ZAxis as below along with the timestamp of
capturing data as below in the completed event. We are changing the double values to
string.
You can save this data for further use for when accelerometer value got
changed.
Let us run the application in debug mode to see value got captured,
When you click on Capture Data button, control will go to Accelerometer reading
changed event. Then each time you move the ball, the Accelerometer reading
changed event will get called.
For your reference, the full code is below,
using
System;
using
System.Windows;
using
Microsoft.Phone.Controls;
using
Microsoft.Devices.Sensors;
namespace
EncryptingandDecryptinginMango
{
public partial
class MainPage
: PhoneApplicationPage
{
public MainPage()
{
InitializeComponent();
}
void accelerometerTaskObject_ReadingChanged(object
sender, AccelerometerReadingEventArgs e)
{
string xCordinate = e.X.ToString("0.00");
string yCordinate = e.Y.ToString("0.00");
string zCordinate = e.Z.ToString("0.00");
DateTimeOffset timeCaptured =
e.Timestamp;
}
private void
btnCaptureData_Click(object sender,
RoutedEventArgs e)
{
var accelerometerTaskObject =
new Accelerometer();
accelerometerTaskObject.ReadingChanged +=
new
EventHandler<AccelerometerReadingEventArgs>
(accelerometerTaskObject_ReadingChanged);
try
{
accelerometerTaskObject.Start();
}
catch
{
//Error in starting the Accelerometer
}
}
}
}
In this way you can work with the Accelerometer API to capture different axis
values. I hope this post was useful. Thanks for reading.
If you find my posts useful you may like to follow me on twitter http://twitter.com/debug_mode
or may like Facebook page of my blog http://www.facebook.com/DebugMode.Net If
you want to see post on a particular topic please do write on FB page or tweet
me about that, I would love to help you.