Skip to content

Instantly share code, notes, and snippets.

@mayur-tendulkar
Created March 9, 2015 05:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mayur-tendulkar/62518ba7e6ded2667d8f to your computer and use it in GitHub Desktop.
Save mayur-tendulkar/62518ba7e6ded2667d8f to your computer and use it in GitHub Desktop.
Using Accelerometer in Windows and Windows Phone Applications
public sealed partial class MainPage : Page
{
private Accelerometer _accelerometer;
public MainPage()
{
this.InitializeComponent();
this.NavigationCacheMode = NavigationCacheMode.Required;
}
/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached.
/// This parameter is typically used to configure the page.</param>
protected override void OnNavigatedTo(NavigationEventArgs e)
{
_accelerometer = Accelerometer.GetDefault();
if (_accelerometer != null)
{
// Establish the report interval
uint minReportInterval = _accelerometer.MinimumReportInterval;
var desiredReportInterval = minReportInterval > 16 ? minReportInterval : 16;
_accelerometer.ReportInterval = desiredReportInterval;
try
{
_accelerometer.ReadingChanged += async (a, b) =>
{
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
txtXAxis.Text = "X axis: " + b.Reading.AccelerationX.ToString("F");
txtYAxis.Text = "Y axis: " + b.Reading.AccelerationY.ToString("F");
txtZAxis.Text = "Z axis: " + b.Reading.AccelerationZ.ToString("F");
});
};
}
catch (Exception ex)
{
throw;
}
}
else
{
new Windows.UI.Popups.MessageDialog("Accelerometer not found", "Error:").ShowAsync();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment