简体   繁体   English

Android手机中的磁力计传感器获取方向

[英]Magnetometer sensor in android mobile to get directions

Here is code which is intended to make my Android mobile phone vibrate when some condition is true. 这是代码,旨在使我的Android手机在某些条件成立时振动。 It should vibrate till azimuth angle (which I get from magnetometer) is not in a given range. 它应该振动直到方位角(我从磁力计得到的)不在给定的范围内。

But no matter in which direction I point the phone, it never vibrates. 但无论我指向哪个方向的电话,它都不会振动。 It enters the if statement but never the while statement. 它输入if语句但不输入while语句。 And the vibrate function is working (ie the phone isn't broken). 并且振动功能正在工作(即手机没有坏掉)。 My purpose is to find north south east west. 我的目的是找到东北西南。

What am I doing wrong? 我究竟做错了什么?

public void onCreate(Bundle savedInstanceState) {
    // some code        
    mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    if (mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD) != null){
        // Success! There's a magnetometer.
        Toast.makeText(
            getApplicationContext(),
            "Detecting magnetic field",
            Toast.LENGTH_LONG).show();
        speakOut("not Working");
    }
    else {
        Toast.makeText(
            getApplicationContext(),
            "not working",
            Toast.LENGTH_LONG).show();
        speakOut("not Working");
    }
    // some code that calls the function
}

some_function(){
    if (//some condition) {
        while (!(85 < azimuth_angle) && !(azimuth_angle < 95)) {
            viberator.vibrate(1000);
            //this should happen when it faces east.
        }
    } 
}

public void onSensorChanged(SensorEvent event) {
    // TODO: Auto-generated method stub
    azimuth_angle = event.values[0];
    pitch_angle = event.values[1];
    roll_angle = event.values[2];
}

registerListener方法丢失,因此您的SensorEventListener不会被触发: http//developer.android.com/reference/android/hardware/SensorManager.html#registerListener (android.hardware.SensorEventListener,android.hardware.Sensor,int)

Azimuth is not a compass direction. 方位角不是罗盘方向。 Here's some code I wrote for a compass sensor. 这是我为罗盘传感器编写的一些代码。 It isn't 100% (it needs a much better filter on it, which I haven't had time or reason to write). 它不是100%(它需要一个更好的过滤器,我没有时间或理由写)。 But it shows the logic of getting the direction, you can work on filtering the return values better yourself. 但它显示了获得方向的逻辑,您可以自己更好地过滤返回值。

Answer to previous question where I posted my code 回答上一个我发布代码的问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM