Sunday, November 6, 2011

WP7 - Accelerometer


WP7 comes in with a built in Accelerometer which measures LINEAR movement and ‘does not contain’ a Gyroscope which measures the angular rate (ROTATION). A combination of these two gives accurate results on device orientation and movement for building the best user experiences while Accelerometer alone results is issues like time delay or noise. The latest version of IPhone (4) has built into it both accelerometer and gyro
The type of applications that you can build is left to your own requirement but some useful scenarios are measurements involving: Walking, Running, Skipping, Earthquakes, Aftershocks, and Vehicle Collisions etc…
The Accelerometer is a vector (x, y, z) which encapsulates direction and magnitude. The magnitude is calculated using SQRT(square(x)+square(y)+square (z)) and measured in G-force a.k.a gravitational forceand 1G=9.8m/s^2. WP7 emulator always returns 0, 0,-1.
Following steps are required to arrive at the simulator based Magnitude which is always 1G but will vary when used with an actual phone.
1) Add the reference Microsoft.Devices.Sensors to your Project from the solution explorer and using directive for the namespace to this extent
2) Create an instance of the class Accelerometer which exposes the methods start, stop, state and dispose which are self-explanatory //Accelerometer acc = new Accelerometer();
3) WMAppManifest.XML needs the following : Capability Name="ID_CAP_SENSORS" (angular tags)if notalready added
4) Set an event handler for the ReadingChanging event which is followed by AccelerometerReadingEventArgs – Event Arguments that expose the properties X, Y , Z and Timestamp which are our main area of interest
5) Create a text block that can take the output of X, Y and Z properties returned after invoking the start method of the instance of the class Accelerometer (created in default constructor)
6) Run the project as described in earlier blogs WP7 and WP7 Orientation and observe the error message related to thread safety of Silverlight in that you are not allowed to access a UI object (TextBlock element) from a non-UI thread (Accelerometer related)
7) Create a delegate as follows:
delegatevoidSetTextBlockTextDelegate(TextBlock myTextBlock, string text);
void SetTextBlockText(TextBlock myTextBlock, string text)
{
myTextBlock.Text = text;
}
8) Use the delegate in the event handler (ReadingChanged) as follows:
void acc_ReadingChanged(object sender, AccelerometerReadingEventArgs args)
{
myTextBlock.Dispatcher.BeginInvoke(new
SetTextBlockTextDelegate(SetTextBlockText),
myTextBlock, str);
}

Where ‘str’ contains the formatted values for X, Y, Z Properties, Magnitude and optionally the Timestamp.

9) Run the project to see the below output from emulator. The red circled area is of interest that depicts X, Y, Z and the Magnitude

No comments:

Post a Comment