UIAccelerometer距离计算

时间:2012-09-12 12:20:48

标签: iphone uiaccelerometer

我使用以下代码计算设备从一个地方移动到另一个地方的距离。是否正确请查看我的代码。

-(void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration
{
    NSDate *now = [NSDate date];
    NSTimeInterval intervalDate = [now timeIntervalSinceDate:now_prev];

    sx = acceleration.x * kFilteringFactor + sx * (1.0 - kFilteringFactor);
    sy = acceleration.y * kFilteringFactor + sy * (1.0 - kFilteringFactor);
    sz = acceleration.z * kFilteringFactor + sz * (1.0 - kFilteringFactor);

    [xLabel setText:[NSString stringWithFormat:@"%.2f",sx]];
    [yLabel setText:[NSString stringWithFormat:@"%.2f",sy]];
    [zLabel setText:[NSString stringWithFormat:@"%.2f",sz]];

    float aValue = sqrtf(sx*sx+sy*sy+sz*sz);
    [gLabel setText:[NSString stringWithFormat:@"%.2f g",aValue]];

    velX += (sx * intervalDate);
    distX += (velX * intervalDate);

    velY += (sy * intervalDate);
    distY += (velY * intervalDate);

    velZ += (sz * intervalDate);
    distZ += (velZ * intervalDate);

    float distance = sqrtf(distX*distX+distY*distY+distZ*distZ);
    [distanceLabel setText:[NSString stringWithFormat:@"%.2f",distance*0.0006213f]];

    now_prev = [now retain];

}

1 个答案:

答案 0 :(得分:0)

有很多理由说明为什么试图与加速器数据保持距离会非常低效。 为了跟踪您的初始位置,您需要将所有加速度值连续地集成到矢量中,并且最好以非常高的采样率(计算中的大间隙会导致不准确)

这个方法本身并不是很难弄清楚(或google); This question explains how to do the maths and pseudocode for such an integration approach