假设 iPhone 放置在平坦的桌子上。我想确定桌面平面的角度,其中角度 0 意味着桌子完全垂直于重力矢量。我正在使用以下公式:
radians = atanf (z / sqrt (x^2 + y^2)
在.h中
double accelerationXAverage;
double accelerationYAverage;
double accelerationZAverage;
double accelerationXSum;
double accelerationYSum;
double accelerationZSum;
int readingsCount;
在他们中
#define kThresholdMovementHigh 0.05
- (void)accelerometer:(UIAccelerometer *)accelerometer
didAccelerate:(UIAcceleration *)acceleration
{
// did device move a lot? if so, reset sums
if (fabsf(acceleration.x - accelerationXAverage) > kThresholdMovementHigh ||
fabsf(acceleration.y - accelerationYAverage) > kThresholdMovementHigh ||
fabsf(acceleration.z - accelerationZAverage) > kThresholdMovementHigh )
{
NSLog(@"deviceDidMove a lot");
accelerationXSum = acceleration.x;
accelerationYSum = acceleration.y;
accelerationZSum = acceleration.z;
readingsCount = 1;
}
else
{
// because the device is at rest, we can take an average of readings
accelerationXSum += acceleration.x;
accelerationYSum += acceleration.y;
accelerationZSum += acceleration.z;
readingsCount ++;
}
accelerationXAverage = accelerationXSum / readingsCount;
accelerationYAverage = accelerationYSum / readingsCount;
accelerationZAverage = accelerationZSum / readingsCount;
float angle = RadiansToDegrees(atanf(accelerationZAverage/sqrtf(pow(accelerationXAverage, 2) + pow(accelerationYAverage, 2)))) + 90;
labelAngle.text = [NSString stringWithFormat:@"%.2f°", angle];
}
我通过计算加速度计读数的平均值来滤除噪音。加速度计更新间隔为 1/60,目前在实验过程中,我让设备静置 10 秒(因此平均为 600 个读数)。
这个公式似乎有效,它给了我关于我的期望的角度。然而,我也期望,如果我尝试将设备旋转到不同的静态位置,同时仍然平放在桌面上,我应该得到相同的答案(因为相对于重力矢量,角度没有改变) 。然而,这不是我尝试时得到的结果。角度相差几度。
我使用的公式正确吗?为什么同一桌面上不同位置的角度会不同?仅仅是误差幅度吗?
I've added an image (from http://gotoandplay.freeblog.hu/ http://gotoandplay.freeblog.hu/) to make sure I'm talking about the same x- y- and z- axis.