In Windows 10 the accelerometer is used to detect the user movement or record the movement in a particular interval. Look at the below image to get a clear idea about accelerometer value change and how it works to identify user movements.
Let’s see the steps
- Create a new Windows 10 universal app.
- Design the UI according to your wish; here I have created one button to start the accelerometer reading.
- Now go to the coding part and write the following code. Firstly, add the following namespace to access the accelerometer sensor API.
using Windows.Devices.Sensors;
- Create one object for the accelerometer,
Accelerometer myAccelerometer;
- Now get the default properties and reading by using GetDefault method.
myAccelerometer = Accelerometer.GetDefault();
Then set interval to read the value from certain interval,
myAccelerometer.ReportInterval = 16;
Now create one event accelerometer reading changes to handle the readings and assign it to your accelerometer.
myAccelerometer.ReadingChanged += MyAccelerometer_ReadingChanged;
Now start the application and get the values from the accelerometer.
Full code looks like the following code.
- public async void startReading()
- {
- myAccelerometer = Accelerometer.GetDefault();
- if (myAccelerometer != null)
- {
-
- uintminReportInterval = myAccelerometer.MinimumReportInterval;
- uintreportInterval = minReportInterval > 16 ? minReportInterval : 16;
- myAccelerometer.ReportInterval = reportInterval;
- myAccelerometer.ReadingChanged += MyAccelerometer_ReadingChanged;
- }
- }
-
- private void MyAccelerometer_ReadingChanged(Accelerometer sender, AccelerometerReadingChangedEventArgsargs)
- {
-
- AccelerometerReading reading = args.Reading;
- string xAxis = String.Format("{0,5:0.00}", reading.AccelerationX);
- string yAxis = String.Format("{0,5:0.00}", reading.AccelerationY);
- string zAxis = String.Format("{0,5:0.00}", reading.AccelerationZ);
-
- }
To read the accelerometer value use AccelerometerReading class.
Read more articles on Windows 10: