2015-06-19 74 views
1

我正在使用加速度传感器来检测我的设备是否平放在桌子上。奇怪的是,即使当我将手机放平或旋转时,它的值始终在90到100之间!这不应该纠正!我错过了什么吗?这里是我的代码:如何知道Android设备是否在桌子上平坦

float[] values = event.values; 
    // Movement 
    float x = values[0]; 
    float y = values[1]; 
    float z = values[2]; 
    float norm_Of_g =(float) Math.sqrt(x * x + y * y + z * z); 

    // Normalize the accelerometer vector 
    x = (x/norm_Of_g); 
    y = (y/norm_Of_g); 
    z = (z/norm_Of_g); 
    int inclination = (int) Math.round(Math.toDegrees(Math.acos(y))); 
    Log.i("tag","incline is:"+inclination); 

    if (inclination < 25 || inclination > 155) 
    { 
     // device is flat 
     Toast.makeText(this,"device flat - beep!",Toast.LENGTH_SHORT); 
    } 

编辑:我使用此代码:How to measure the tilt of the phone in XY plane using accelerometer in Android

+0

您应该使用'log.i(,)'而不是'System.out'这是用于终端的 –

+0

加速度计通常比人类更敏感。我不得不禁用我的笔记本电脑的加速度计,因为即使当我按下按键时,它也会将不需要的输入提供给许多应用程序。 – o11c

+0

默认情况下'System.out'是行缓冲的,所以输出只有在发送换行符时才可见。 – o11c

回答

1

您使用的是the answer you linked中使用的y轴而不是z轴。

ACOS的值将是接近零,当参数是近的一个(或接近180度时接近负一),如在这样的画面:

Arccos(x)

因此,您的倾斜只有当y轴归一化到大约一个或负值时,例如当它与重力平行时(因此,该装置“站起来”),它将接近零(或180)度。

如果没有其他错误,只需切换:

int inclination = (int) Math.round(Math.toDegrees(Math.acos(y))); 

int inclination = (int) Math.round(Math.toDegrees(Math.acos(z))); 

应该这样做。

0

我用这个页面Motion Sensors

public void onSensorChanged(SensorEvent event){ 
    // In this example, alpha is calculated as t/(t + dT), 
    // where t is the low-pass filter's time-constant and 
    // dT is the event delivery rate. 

    final float alpha = 0.8; 

    // Isolate the force of gravity with the low-pass filter. 
    gravity[0] = alpha * gravity[0] + (1 - alpha) * event.values[0]; 
    gravity[1] = alpha * gravity[1] + (1 - alpha) * event.values[1]; 
    gravity[2] = alpha * gravity[2] + (1 - alpha) * event.values[2]; 

    // Remove the gravity contribution with the high-pass filter. 
    linear_acceleration[0] = event.values[0] - gravity[0]; 
    linear_acceleration[1] = event.values[1] - gravity[1]; 
    linear_acceleration[2] = event.values[2] - gravity[2]; 
} 
上的代码的详细信息

这样做的目的是在加速度计值中分解重力(通过重复测量),仅留下每个方向上的加速度分量。

重力是沿着每个轴测量的,所以一旦您知道哪个轴表示设备处于平坦状态,您只需检查大部分重力是否落在该轴上即可。这意味着该设备平放在桌子上。

您还可以查看线性加速度以确保设备不移动。

+1

谢谢,但你如何得到数组gravity []?它是如何初始化的 –

+1

我刚把它初始化为0,它稳定很快 private float [] gravity = new float [] {0,00}; – dangVarmit

相关问题