Android trouble getting compass direction - android

I am trying to get the users magnetic heading using the SensorEventListener. Sadly on Android this seams to be a bit of a hassle.
On my HTC, my readings seam to be fairly accurate. On my Samsung Galaxy S3, the readings are totally random. I know there must be something wrong with my class though since the compass apps from the Play store seam to work just fine.
My code is:
public class HeadingSensor implements SensorEventListener {
private static final String LOG_TAG = "sw_HeadingSensor";
private SensorManager mSensorManager;
private long mLastHeadingUpdate;
private int mMinUpdateFrequency = 500;//milliseconds
private HeadingListener mCallback;
private float[] mGravity;
private float[] mGeomagnetic;
public interface HeadingListener {
public void headingChanged(int heading);
}
public HeadingSensor(Context context, HeadingListener headingListener) {
mCallback = headingListener;
mSensorManager = (SensorManager)context.getSystemService(Context.SENSOR_SERVICE);
}
public void registerListener() {
Log.d(LOG_TAG, "listener registered");
mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD), SensorManager.SENSOR_DELAY_UI);
mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_UI);
}
public void unregisterListener() {
Log.d(LOG_TAG, "listener unregistered");
mSensorManager.unregisterListener(this);
}
#Override
public void onSensorChanged(SensorEvent sensorEvent) {
if (sensorEvent.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
mGravity = sensorEvent.values;
}
if (sensorEvent.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
mGeomagnetic = sensorEvent.values;
}
if (mGravity != null && mGeomagnetic != null) {
float R[] = new float[9];
float I[] = new float[9];
boolean success = SensorManager.getRotationMatrix(R, I, mGravity, mGeomagnetic);
if (success) {
long currentTime = System.currentTimeMillis();
if ((currentTime - mLastHeadingUpdate) > mMinUpdateFrequency) {
mLastHeadingUpdate = currentTime;
float orientation[] = new float[3];
SensorManager.getOrientation(R, orientation);
float azimuthInRadians = orientation[0];
int azimuthInDegress = (int)(Math.toDegrees(azimuthInRadians) + 360) % 360;
if (null != mCallback) {
mCallback.headingChanged(azimuthInDegress);
}
}
}
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) { }
}
I have read as many tutorials, references, etc as possible but I can't find a good way to get the compass heading. Can someone show me what is wrong with this class?

You should use TYPE_GRAVITY instead of TYPE_ACCELEROMETER else you should low pass filter TYPE_ACCELEROMETER. Your problem lies mainly in
mGravity = sensorEvent.values;
and
mGeomagnetic = sensorEvent.values;
Since sensorEvent is a local variable and either mGravity or mGeomagnetic points to this value, either of these can be anything by the next time onSensorChanged is called. It should be
mGravity = sensorEvent.values.clone();
and
mGeomagnetic = sensorEvent.values.clone();
You can look at my answer at Android getOrientation Azimuth gets polluted when phone is tilted

Related

Logic for finding qibla direction using accelerometer and magnetic field sensors

I am trying to implement the logic for finding the qibla direction.
I used Sensor.TYPE_ORIENTATION and copied the code from here
mSensorManager = (SensorManager) context.getSystemService(SENSOR_SERVICE);
sensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
but I found that the Sensor.TYPE_ORIENTATION is deprecated and instead, I used accelerometer and magnetic field sensors from here
here is my code now
private void registerSensor() {
mySensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
accelerometer = mySensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
magnetometer = mySensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
mySensorManager.registerListener(mySensorEventListener, accelerometer, SensorManager.SENSOR_DELAY_UI);
mySensorManager.registerListener(mySensorEventListener, magnetometer, SensorManager.SENSOR_DELAY_UI);
}
private SensorEventListener mySensorEventListener = new SensorEventListener() {
float degree;
float head;
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
#Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
if (lastKnownLocation == null || image == null || arrow == null) {
return;
}
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER)
mGravity = event.values;
if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD)
mGeomagnetic = event.values;
if (mGravity != null && mGeomagnetic != null) {
float R[] = new float[9];
float I[] = new float[9];
boolean success = SensorManager.getRotationMatrix(R, I, mGravity, mGeomagnetic);
if (success) {
float orientation[] = new float[3];
SensorManager.getOrientation(R, orientation);
degree = orientation[2]; // orientation contains: azimut, pitch and roll
head = orientation[0];
}
}
I am trying to get the degree and head. what am I doing wrong here?

Accelerometer values to degrees

I wrote the following code,where the values of the accelerometer are shown in x,y,z during rotation.
public class MainActivity extends AppCompatActivity implements SensorEventListener {
private TextView xText,yText,zText;
private Sensor mySensor;
private SensorManager SM;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Creating the Sensor Manager
SM = (SensorManager)getSystemService(SENSOR_SERVICE);
// Accelerometer Sensor
mySensor = SM.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
// Register sensor Listener
SM.registerListener(this, mySensor, SensorManager.SENSOR_DELAY_NORMAL);
// Assign TextView
xText = (TextView)findViewById(R.id.xText);
yText = (TextView)findViewById(R.id.yText);
zText = (TextView)findViewById(R.id.zText);
}
#Override
public void onSensorChanged(SensorEvent sensorEvent) {
xText.setText("X: " + sensorEvent.values[0]);
yText.setText("Y: " + sensorEvent.values[1]);
zText.setText("Z: " + sensorEvent.values[2]);
}
#Override
public void onAccuracyChanged(Sensor sensor, int i) {
}
}
Now I want to convert the values I get from the SensorEvents to degrees. I looked at various questions here,but I got confused.
double x = sensorEvent.values[0];
double y = sensorEvent.values[1];
double z = sensorEvent.values[2];
There should be a formula that takes the above values and convert them in degrees.
Any ideas?
#Override
public void onSensorChanged(SensorEvent sensorEvent) {
//xText.setText("X: " + sensorEvent.values[0]);
//yText.setText("Y: " + sensorEvent.values[1]);
//zText.setText("Z: " + sensorEvent.values[2]);
double x = sensorEvent.values[0];
double y = sensorEvent.values[1];
double z = sensorEvent.values[2];
double pitch = Math.atan(x/Math.sqrt(Math.pow(y,2) + Math.pow(z,2)));
double roll = Math.atan(y/Math.sqrt(Math.pow(x,2) + Math.pow(z,2)));
//convert radians into degrees
pitch = pitch * (180.0/3.14);
roll = roll * (180.0/3.14) ;
yText.setText(String.valueOf(pitch));
zText.setText(String.valueOf(roll));
}
Now I want to convert the values I get from the SensorEvents to degrees
The unit of the value you get from TYPE_ACCELEROMETER is m/s^2, thus trying to convert to degree does not make sense.
Your pitch and roll calculations do not seem right. For the correct calculation see the method processSensorData(DProcessedSensorEvent.DProcessedSensorEventBuilder builder) in the DSensorEventProcessor class at https://github.com/hoananguyen/dsensor/blob/master/dsensor/src/main/java/com/hoan/dsensor_master/DSensorEventProcessor.java
To convert pitch and roll to degrees use Math.toDegrees(valueToConvert)
Youll need to register for the TYPE_ACCELEROMETER, but also for TYPE_MAGNETIC_FIELD and than you can leverage SensorManager built-in method for your help:
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER)
gravity = event.values;
if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD)
geomagnetic = event.values;
if (mGravity != null && geomagnetic != null) {
float R[] = new float[9];
float I[] = new float[9];
boolean success = SensorManager.getRotationMatrix(R, I, gravity, geomagnetic);
if (success) {
float orientation[] = new float[3];
SensorManager.getOrientation(R, orientation);
myAzimut = orientation[0]; // myAzimut is The geomagnetic inclination angle in radians.
}
}
}
You can learn all additional information by reading SensorManagersource code comments.
your code seem right. use Math.PI in (180.0/3.14) to get more accurate results.

how to detect magnetic interference

I want to compute the compass' direction, so I use the following code:
SensorManager mManager = (SensorManager)mContext.getSystemService(Context.SENSOR_SERVICE);
Sensor accelerometer = mManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
Sensor magnetometer = mManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
mManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
mManager.registerListener(this, magnetometer, SensorManager.SENSOR_DELAY_NORMAL);
private float mR[] = new float[9];
private float mI[] = new float[9];
float mOrientation[] = new float[3];
....
public void onSensorChanged(SensorEvent event)
{
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER)
mGravity = event.values;
if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD)
mGeomagnetic = event.values;
if (mGravity != null && mGeomagnetic != null) {
boolean success = SensorManager.getRotationMatrix(mR, mI, mGravity, mGeomagnetic);
if (success) {
SensorManager.getOrientation(mR, mOrientation);
int azimut = (int) (mOrientation[0]*180/3.14159f); // This is the data
}
}
}
It usually works fine. It does not work when there is an interference with the magnetic field - for example under my car radio. In that case - I get a wrong constant reading.
how can I detect magnetic interference?

Get device angle by using getOrientation() function

I was using Sensor.TYPE_ORIENTATION to determine current angle of device but TYPE_ORIENTATION is deprecated on API version 8. In SensorManager manual it refers to getOrientation() function in order to use TYPE_ORIENTATION.
Here is the manual
Here is my old code :
public void onSensorChanged(SensorEvent event) {
Log.d("debug","Sensor Changed");
if (event.sensor.getType()==Sensor.TYPE_ORIENTATION) {
Log.d("debug",Float.toString(event.values[0]));
float mAzimuth = event.values[0];
float mPitch = event.values[1];
float mRoll = event.values[2];
Log.d("debug","mAzimuth :"+Float.toString(mAzimuth));
Log.d("debug","mPitch :"+Float.toString(mPitch));
Log.d("debug","mRoll :"+Float.toString(mRoll));
}
}
I'm really confused about using getOrientation() function, can anyone please show me an example how to get the angles?
You now use two sensors (ACCELEROMETER and MAGNETIC_FIELD) to get that information. See blog post for more detail.
public class CompassActivity extends Activity implements SensorEventListener {
private SensorManager mSensorManager;
Sensor accelerometer;
Sensor magnetometer;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(mCustomDrawableView); // Register the sensor listeners
mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
accelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
magnetometer = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
}
protected void onResume() {
super.onResume();
mSensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_UI);
mSensorManager.registerListener(this, magnetometer, SensorManager.SENSOR_DELAY_UI);
}
protected void onPause() {
super.onPause();
mSensorManager.unregisterListener(this);
}
public void onAccuracyChanged(Sensor sensor, int accuracy) { }
float[] mGravity;
float[] mGeomagnetic;
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER)
mGravity = event.values;
if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD)
mGeomagnetic = event.values;
if (mGravity != null && mGeomagnetic != null) {
float R[] = new float[9];
float I[] = new float[9];
boolean success = SensorManager.getRotationMatrix(R, I, mGravity, mGeomagnetic);
if (success) {
float orientation[] = new float[3];
SensorManager.getOrientation(R, orientation);
azimut = orientation[0]; // orientation contains: azimut, pitch and roll
}
}
}
}
Permissions:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
Regarding your second question. When you are registering your sensor listeners, change your code to read:
protected void onResume() {
super.onResume();
mSensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
mSensorManager.registerListener(this, magnetometer, SensorManager.SENSOR_DELAY_NORMAL);
}
Google has a great demo app for orientation in their google-developer-training series called TiltSpot. Because it has an Apache license, I've taken the liberty of turning it into a small library called johnnylambada-orientation that makes getting orientation as simple adding this to your activity:
getLifecycle().addObserver(new OrientationReporter(this, (a, p, r) -> {
Log.i("orientation","a="+a+" p="+p+" r="+r);
}));
My Answer is for those who getting jumping values of heading. For further instruction let me know in the comment.
Sensor accelerometer;
Sensor magnetometer;
private float[] mGravity = new float[3];
private float[] mGeomagnetic = new float[3];
private float[] Rv = new float[9];
private float[] I = new float[9];
class MapsActivity
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, SensorEventListener{
onSensorChanged(SensorEvent event)
#Override
public void onSensorChanged(SensorEvent event) {
synchronized (this) {
float INITIAL_ALPHA = 0.97f;
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
mGravity[0] = INITIAL_ALPHA * mGravity[0] + (1 - INITIAL_ALPHA)
* event.values[0];
mGravity[1] = INITIAL_ALPHA * mGravity[1] + (1 - INITIAL_ALPHA)
* event.values[1];
mGravity[2] = INITIAL_ALPHA * mGravity[2] + (1 - INITIAL_ALPHA)
* event.values[2];
}
if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
mGeomagnetic[0] = INITIAL_ALPHA * mGeomagnetic[0] + (1 - INITIAL_ALPHA)
* event.values[0];
mGeomagnetic[1] = INITIAL_ALPHA * mGeomagnetic[1] + (1 - INITIAL_ALPHA)
* event.values[1];
mGeomagnetic[2] = INITIAL_ALPHA * mGeomagnetic[2] + (1 - INITIAL_ALPHA)
* event.values[2];
if (Math.abs(mGeomagnetic[2]) > Math.abs(mGeomagnetic[1])) {
magStrength = Math.round(Math.abs(mGeomagnetic[2]));
} else {
magStrength = Math.round(Math.abs(mGeomagnetic[1]));
}
}
boolean success = SensorManager.getRotationMatrix(Rv, I, mGravity, mGeomagnetic);
if (success) {
float[] orientation = new float[3];
SensorManager.getOrientation(Rv, orientation);
azimuth = (float) Math.toDegrees(orientation[0]);
azimuth = (azimuth + 360) % 360;
// Log.d(TAG, "azimuth (deg): " + azimuth);
float degree = Math.round(azimuth);
// create a rotation animation (reverse turn degree degrees)
RotateAnimation ra = new RotateAnimation(
currentDegree,
-degree,
Animation.RELATIVE_TO_SELF, 0.5f,
Animation.RELATIVE_TO_SELF,
0.5f);
ra.setDuration(500);
ra.setFillAfter(true);
ra.setRepeatCount(0);
binding.compassImage.startAnimation(ra);
showDirection(degree);
currentDegree = -degree;
}
}
}
onAccuracyChanged
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
onResume()
#Override
protected void onResume() {
super.onResume();
if (mSensorManager == null) {
mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
accelerometer =
mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
magnetometer =
mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
}
mSensorManager.registerListener(this, accelerometer,
SensorManager.SENSOR_DELAY_UI);
mSensorManager.registerListener(this, magnetometer,
SensorManager.SENSOR_DELAY_UI);
}
onPause()
#Override
protected void onPause() {
super.onPause();
mSensorManager.unregisterListener(MapsActivity.this);
}

Android Compass Bearing

I am trying to get the compass bearing in degrees (i.e. 0-360) using the following method:
float[] mGravity;
float[] mGeomagnetic;
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER)
mGravity = event.values;
if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD)
mGeomagnetic = event.values;
if (mGravity != null && mGeomagnetic != null) {
float R[] = new float[9];
float I[] = new float[9];
boolean success = SensorManager.getRotationMatrix(R, I, mGravity,
mGeomagnetic);
if (success) {
float orientation[] = new float[3];
SensorManager.getOrientation(R, orientation);
float azimut = orientation[0];
bearing.setText("Bearing: "+ azimut);
}
}
}
The azimuth value (i.e. orientation[0]) should be 0<=azimuth<360 but I am getting only values from -3 to 3 as I rotate my device. Can someone please tell me what the problem might be please?
The values are in radian, you have to convert to degree of arc
int azimut = (int) Math.round(Math.toDegrees(orientation[0]));
It is true that it is in Radians. Thanks Hoan. I added some logic to get that bearing in degrees from 0 to 360 becuase if I only converted it to degrees, I was getting values from -180 to 180.
float azimuthInRadians = orientation[0];
float azimuthInDegress = (float)Math.toDegrees(azimuthInRadians)+360)%360;
// This answer applies to Google Maps api v2.
// It is possible by registering your application with Sensor Listener for Orientation and get the
// angle relative to true north inside onSensorChanged and update camera accordingly.
// Angle can be used for bearing. Following code can be used:
// Instead of using Sensor.TYPE_ORIENTATION try using getOrinetation api. Sensor.TYPE_ORIENTATION
// has been deprecated.
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
if (sensorManager != null)
sensorManager.registerListener(this,
sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION),
SensorManager.SENSOR_DELAY_GAME);
}
public void onSensorChanged(SensorEvent event) {
float compassBearingRelativeToTrueNorth = Math.round(event.values[0]);
Log.d(TAG, "Degree ---------- " + degree);
updateCamera(compassBearingRelativeToTrueNorth);
}
private void updateCamera(float bearing) {
CameraPosition oldPos = googleMap.getCameraPosition();
CameraPosition pos = CameraPosition.builder(oldPos).bearing(bearing)
.build();
googleMap.moveCamera(CameraUpdateFactory.newCameraPosition(pos));
}

Categories

Resources