【问题标题】:Do I need to use NSTimer to get data from gyroscope iOS?我是否需要使用 NSTimer 从陀螺仪 iOS 获取数据?
【发布时间】:2012-12-21 06:25:27
【问题描述】:

现在我正在使用以下代码从设备的陀螺仪中获取欧拉值。这是应该如何使用的吗?或者有没有更好的方法不使用 NSTimer?

- (void)viewDidLoad {
[super viewDidLoad];
CMMotionManager *motionManger = [[CMMotionManager alloc] init];
[motionManger startDeviceMotionUpdates];

NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:(1/6) target:self selector:@selector(read) userInfo:nil repeats:YES];
}

- (void)read {
CMAttitude *attitude;
CMDeviceMotion *motion = motionManger.deviceMotion;
attitude = motion.attitude;
int yaw = attitude.yaw; 
}

【问题讨论】:

  • 我的目标是持续监控偏航值以确定设备是否沿其中心旋转了 360 度。最有效的方法是什么?

标签: objective-c ios nstimer gyroscope core-motion


【解决方案1】:

你可以用这个...

    [motionManager startDeviceMotionUpdatesToQueue:[NSOperationQueue currentQueue] withHandler:^(CMDeviceMotion *motion, NSError *error)
 {
     CMAttitude *attitude;
     attitude = motion.attitude;
     int yaw = attitude.yaw; 
 }];

【讨论】:

    【解决方案2】:

    直接引用the documentation:

    以指定的间隔处理运动更新

    接收运动数据 在特定的时间间隔内,应用程序调用一个“start”方法,该方法需要一个 操作队列(NSOperationQueue 的实例)和块处理程序 用于处理这些更新的特定类型。运动数据为 传递给块处理程序。更新频率确定 通过“间隔”属性的值。

    [...]

    设备运动。设置 deviceMotionUpdateInterval 属性以指定 更新间隔。致电或 startDeviceMotionUpdatesUsingReferenceFrame:toQueue:withHandler: 或 startDeviceMotionUpdatesToQueue:withHandler: 方法,传入一个 CMDeviceMotionHandler 类型的块。用前一种方法(新 iOS 5.0),您可以指定要用于 态度估计。旋转速率数据作为 CMDeviceMotion 对象。

    例如

    motionManger.deviceMotionUpdateInterval = 1.0/6.0; // not 1/6; 1/6 = 0
    [motionManager 
        startDeviceMotionUpdatesToQueue:[NSOperationQueue mainQueue]
        withHandler:
            ^(CMDeviceMotion *motion, NSError *error)
             {
                 CMAttitude *attitude;
                 attitude = motion.attitude;
                 int yaw = attitude.yaw; 
             }];
    

    我只是懒惰地使用了主队列,但这仍然可能是比 NSTimer 更好的解决方案,因为它会给运动管理器一个明确的线索,告诉你多久需要更新一次。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多