在iOS中查找速度和加速度

时间:2014-05-14 07:08:19

标签: ios iphone

请在Accelerometer中使用iPhone查找加速度和速度(速度)时建议我。

使用以下代码测量加速度和速度。但是没有得到正确的速度值。

CMMotionManager *motionManager;
motionManager = [[CMMotionManager alloc] init];
motionManager.accelerometerUpdateInterval  = 1.0/10.0;
[motionManager startDeviceMotionUpdates];
CMMotionManager *mManager = [[CMMotionManager alloc] init];


    [mManager setAccelerometerUpdateInterval:0.1];// Update at 10Hz
    [mManager startAccelerometerUpdatesToQueue:[NSOperationQueue mainQueue] withHandler:^(CMAccelerometerData *accelerometerData, NSError *error) {

        motionManager = mManager;

        gravX = (accelerometerData.acceleration.x * kFilteringFactor) + (gravX * (1.0 - kFilteringFactor));
        gravY = (accelerometerData.acceleration.y * kFilteringFactor) + (gravY * (1.0 - kFilteringFactor));
        gravZ = (accelerometerData.acceleration.z * kFilteringFactor) + (gravZ * (1.0 - kFilteringFactor));

        UIAccelerationValue accelX = accelerometerData.acceleration.x - ( (accelerometerData.acceleration.x * kFilteringFactor) + (gravX * (1.0 - kFilteringFactor)) );

        UIAccelerationValue accelY = accelerometerData.acceleration.y - ( (accelerometerData.acceleration.y * kFilteringFactor) + (gravY * (1.0 - kFilteringFactor)) );
        UIAccelerationValue accelZ = accelerometerData.acceleration.z - ( (accelerometerData.acceleration.z * kFilteringFactor) + (gravZ * (1.0 - kFilteringFactor)) );

        accelX *= 9.81f;
        accelY *= 9.81f;
        accelZ *= 9.81f;


        UIAccelerationValue vector = sqrt(pow(accelX,2)+pow(accelY,2)+pow(accelZ, 2));
        UIAccelerationValue acce = vector - prevVelocity;
        UIAccelerationValue velocity = (((acce - prevAcce)/2) * (1/kAccelerometerFrequency)) + prevVelocity;
        NSLog(@"Prev Velocity: %f",prevVelocity);
        NSLog(@"Velocity :%f",velocity);

        prevAcce = acce;
        prevVelocity = velocity;


        self.accelerationLbl.text = [NSString stringWithFormat:@"%.2f",vector];
        self.velocityLbl.text = [NSString stringWithFormat:@"%.2f",velocity];



    }];

1 个答案:

答案 0 :(得分:0)

试试这段代码:

使用ViewDidLoad方法

[self setAccelerometerEnabled:NO];
[[UIAccelerometer sharedAccelerometer] setUpdateInterval:1/60]; // this is for your Accelerometer speed

Accelerometer委托方法:

- (void) accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration
{    
   CGPoint playerPos = [imageview position];
   playerPos.x += kXFilterFactor * acceleration.y;
   playerPos.y += kYFilterFactor * -acceleration.x;

   if (playerPos.x < 10)
   {
      playerPos.x = 10;
   } else if (playerPos.x > self.view.frame.size.width - 10)
   {
      playerPos.x = self.view.frame.size.width - 10;
   }

   if (playerPos.y< 10)
   {
      playerPos.y = 10;
   } else if (playerPos.y > self.view.frame.size.height - 10)
   {
      playerPos.y = self.view.frame.size.height - 10;
   }
   [imageview setPosition:playerPos];
}