Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get data from Core Motion on iOS

i have trouble getting the accelerometer data from core motion manager...i followed the documentation and it still doesn't work :(

self.manager = [[CMMotionManager alloc] init];
self.manager.accelerometerUpdateInterval = 0.01;
[self.manager startAccelerometerUpdates];

CMAccelerometerData *newestAccel = self.manager.accelerometerData;

int x, y, z;
x = newestAccel.acceleration.x;
y = newestAccel.acceleration.y;
z = newestAccel.acceleration.z;

any help would be very much appreciated!!

like image 262
Chris Lin Avatar asked Feb 06 '12 14:02

Chris Lin


1 Answers

I managed to make it work using blocks, here's the code that I managed to get working:

NSOperationQueue *theQueue = [[NSOperationQueue alloc] init];

_returnedData = [[CMAccelerometerData alloc] init];
_motionManager = [[CMMotionManager alloc] init];

[_motionManager startAccelerometerUpdatesToQueue:theQueue withHandler:^(CMAccelerometerData *accelerometerData, NSError *error) {

    _returnedData = _motionManager.accelerometerData;

    int x = _motionManager.accelerometerData.acceleration.x;
    int y = _returnedData.acceleration.y;

    NSLog(@"X: %i, Y: %i", x, y);
}];

You can either access the accelerometerData.accelleration directly from the CAMotionManager or by creating an instance of CMAccelerometerData and assigning the variables to that. Hope this helps.

like image 81
Carl Goldsmith Avatar answered Oct 13 '22 00:10

Carl Goldsmith