我正在使用 CoreMotion API,我想每 10 毫秒(100 赫兹)保存一次加速度计的值。到目前为止我获得的更新间隔并不准确。这是我得到的更新间隔示例(以秒为单位):
0.010414999997
0.0105919999769
0.0117060000193
0.0198359999922
0.00989700001082
0.0100809999858
0.0100519999978
0.0106810000143
0.010420000006
0.0107459999854
0.0105899999908
0.0105130000156
0.0104829999909
0.0107439999992
0.010391000018
0.0105859999894
0.0102320000005
0.010134000011
0.0101929999946
0.010666999995
0.00996399999713
0.0123709999898
0.0181950000115
0.0107940000016
0.00988500000676
0.0101469999936
0.0103529999906
如您所见,有些值高于 10 毫秒。
更多信息:
- Xcode 3.2.6 / iOS4.3 / armv7
- 在 iPhone4 iOS5.1 和 iPodTouch4 iOS4.3.3 上测试
- 源代码:
-(void) viewDidLoad {
started = NO;
motionManager = [[CMMotionManager alloc] init];
if ([motionManager isAccelerometerAvailable]) {
motionManager.accelerometerUpdateInterval = 0.01; //100Hz
motionQueue = [[NSOperationQueue alloc] init];
[motionQueue setMaxConcurrentOperationCount:1]; // Serial operation queue
} else {
NSLog(@"Accelerometer is not available!\n");
}
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSMutableString *documentsDirectory = [[NSMutableString alloc] initWithString:[paths objectAtIndex:0]];
path = [[NSMutableString alloc] init];
[path setString:[NSString stringWithFormat:@"%@/timestamp.cap", documentsDirectory]];
NSFileManager *fileManager = [NSFileManager defaultManager];
[fileManager removeItemAtPath:path error:NULL];
[fileManager createFileAtPath:path contents:nil attributes:nil];
}
- (IBAction) startStopButton:(id) sender {
if(!started) {
started = YES;
[sender setTitle:@"Stop" forState:UIControlStateNormal];
CMAccelerometerHandler dataHandler = ^(CMAccelerometerData *accelerometerData, NSError *error) {
NSString *content = [NSString stringWithFormat:@"%f\n", accelerometerData.timestamp];
NSFileHandle *fh = [NSFileHandle fileHandleForWritingAtPath:path];
[fh seekToEndOfFile];
[fh writeData:[content dataUsingEncoding:NSUTF8StringEncoding]];
[fh closeFile];
};
[motionManager startAccelerometerUpdatesToQueue:motionQueue withHandler:dataHandler];
} else {
started = NO;
[motionManager stopAccelerometerUpdates];
[motionQueue waitUntilAllOperationsAreFinished];
[sender setTitle:@"Start" forState:UIControlStateNormal];
}
}
预先感谢您的回答。