Showing posts with label beginner. Show all posts
Showing posts with label beginner. Show all posts

Thursday, 23 January 2014

Android Accelerometer vs Windows Accelerometer part 2

We have accessed accelerometer readings on our android devices why don't we see how this is done on a windows phone development environment right quick and easy.

Create your windows phone project; NOTE this will work on a windows phone 7 device too so you can select the windows phone 7 emulator, as a matter of fact i will be running this on a wp7 emulator.

First we drag a TextBlock and name it readings(you can name it what ever) note i also changed my default text to 0.0, because i felt it way cooler...
<textblock horizontalalignment="Left" margin="79,106,0,0" name="reading" text="0.00" textwrapping="Wrap" verticalalignment="Top">
</textblock>

Next you need to add these references:

using Microsoft.Devices.Sensors;
using Microsoft.Xna.Framework;

If you can't find these references just right click references and select add references, you will get a list of references select those to.
We then have to create our Accelerometer variable
Accelerometer accelerometer;

with that setup the next thing we need to do is check if our device has an accelerometer sensor
if (!Accelerometer.IsSupported)
            {
                MessageBox.Show("No Accelerometer sensor found");
            }

now we have checked for our sensor and given the user a message if his device does not have an accelerometer, we then have to initialize our accelerometer variable, set the update/refresh time, create our event handler and then start our accelerometer see code below
if (accelerometer == null)
            {
                //initialize the accelerometer variable
                accelerometer = new Accelerometer();
                //set the update delay in milliseconds
                accelerometer.TimeBetweenUpdates = TimeSpan.FromMilliseconds(10);
                accelerometer.CurrentValueChanged += new EventHandler>(accelerometer_ValueChanged);
                //start our sensor
                accelerometer.Start();
            }

so if there is an accelerometer device and we are not getting any data (that is, if it is offline) then we do the above.
we then update our UI thread with the following code:
void accelerometer_ValueChanged(object sender, SensorReadingEventArgs e)
        {
            Dispatcher.BeginInvoke(() => UpdateUI(e.SensorReading));
        }

Great you have it this far, believe it or not we are getting our data from the accelerometer we for those with doubt why don't we display this data in our TextBlock through our UpdateUI method.
private void UpdateUI(AccelerometerReading accelerometerReading)
        {
            Vector3 acceleration = accelerometerReading.Acceleration;

            reading.Text = "X: " + acceleration.X.ToString() + "\nY:" + acceleration.Y.ToString() + "\nZ: " + acceleration.Z.ToString();
        }

You can now run and test the code in the emulator, if you don't know how this is done just run the code and click the double arrow button pointing towards the right you will see a new window with some tabs, select accelerometer tab and drag the orange circle in the middle of the virtual phone.
you should see your readings
Full Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Devices.Sensors;
using Microsoft.Xna.Framework;

namespace PhoneApp3
{
    public partial class MainPage : PhoneApplicationPage
    {
        Accelerometer accelerometer;
        // Constructor
        public MainPage()
        {
            InitializeComponent();

            // Sample code to localize the ApplicationBar
            //BuildLocalizedApplicationBar();
            if (!Accelerometer.IsSupported)
            {
                MessageBox.Show("No Accelerometer");
            }
            if (accelerometer == null)
            {
                accelerometer = new Accelerometer();
                accelerometer.TimeBetweenUpdates = TimeSpan.FromMilliseconds(10);
                accelerometer.CurrentValueChanged += new EventHandler>(accelerometer_ValueChanged);
                accelerometer.Start();
            }

            
        }

        void accelerometer_ValueChanged(object sender, SensorReadingEventArgs e)
        {
            Dispatcher.BeginInvoke(() => UpdateUI(e.SensorReading));
        }

        private void UpdateUI(AccelerometerReading accelerometerReading)
        {
            Vector3 acceleration = accelerometerReading.Acceleration;

            reading.Text = "X: " + acceleration.X.ToString() + "\nY:" + acceleration.Y.ToString() + "\nZ: " + acceleration.Z.ToString();
       
    }
}

Our output

Android Accelerometer vs Windows Accelerometer part 1

Hello guys i will like to show you how to get accelerometer readings from android and windows phone devices, as for this part we will focus on Android devices.
So we will be using a TextView to display the data.
Setup your project and open the activity_main.xml and edit the default Hello world text to:
<TextView
android:id="@+id/display_reading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>

That is all we need to do to our activity_main.xml
Next we have to create a SensorManager and Sensor variable as follows

Sensor sensor;
//help us manage sensor components
SensorManager sm
TextView displayReading;
We then configure our service and select the type of service we wish to utilize in this case the sensor service, after that we then select a sensor (Accelerometer)
//setup a sensor service
sm = (SensorManager)getSystemService(SENSOR_SERVICE);
//select the sensor we wish to use
sensor = sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
	
sm.registerListener(this, sensor, SensorManager.SENSOR_DELAY_NORMAL);
		
displayReading = (TextView)findViewById(R.id.display_reading);
you will notice we implemented a sensor manager listener to sm.registerListener after doing this you will get an error which can be resolved by implementing SensorEventListener. After doing this you will get another error which is resolved by implementing to methods; onSensorChanged() and onAccuracyChanged()

We are all done with setting things up now we have to get our readings, which we implement in the onSensorChanged() method:
@Override
	public void onSensorChanged(SensorEvent event) {
		// TODO Auto-generated method stub
		displayReading.setText("X"+event.values[0]+"\nY"+event.values[1]+"\nZ"+event.values[2]);
		
	}

The Full code
package com.example.accelerometer;

import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity implements SensorEventListener{

	//this class help select a particular sensor
	Sensor sensor;
	//help us manage sensor components
	SensorManager sm;
	
	TextView displayReading;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		//setup a sensor service
		sm = (SensorManager)getSystemService(SENSOR_SERVICE);
		//select the sensor we wish to use
		sensor = sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
		
		sm.registerListener(this, sensor, SensorManager.SENSOR_DELAY_NORMAL);
		
		displayReading = (TextView)findViewById(R.id.display_reading);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public void onAccuracyChanged(Sensor arg0, int arg1) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onSensorChanged(SensorEvent event) {
		// TODO Auto-generated method stub
		displayReading.setText("X"+event.values[0]+"\nY"+event.values[1]+"\nZ"+event.values[2]);
		
	}

}


With all that done you can now test "on a real device" since the emulator can not simulate accelerometer behavior, i will get a snapshot of it, thanks.