michaelsnowden
michaelsnowden

Reputation: 6202

How to access magnetometer data

Following the docs, here is my attempt to access magnetometer data. Needless to say, it doesn't work.

I've gotten gyroscope and accelerometer data to work using the exact same approach, but for some reason, I get all zeroes in each axis using this one.

 motionManager = [[CMMotionManager alloc] init];


[motionManager startDeviceMotionUpdates];
[motionManager startMagnetometerUpdatesToQueue:
 [NSOperationQueue currentQueue] withHandler:^(CMMagnetometerData *magnetometerData, NSError *error) {
     double x = motionManager.deviceMotion.magneticField.field.x;
     double y = motionManager.deviceMotion.magneticField.field.y;
     double z = motionManager.deviceMotion.magneticField.field.z;

     self.magnetometerDataLabel.text = [NSString stringWithFormat:@"{%8.4f, %8.4f, %8.4f}", x, y, z];
 }];
motionManager.magnetometerUpdateInterval = 1.0 / 60.0;

What am I missing?

Upvotes: 0

Views: 1129

Answers (1)

michaelsnowden
michaelsnowden

Reputation: 6202

This worked:

[motionManager startDeviceMotionUpdatesUsingReferenceFrame:CMAttitudeReferenceFrameXArbitraryCorrectedZVertical toQueue:[NSOperationQueue currentQueue] withHandler:^(CMDeviceMotion *motion, NSError *error) {
    double x = motionManager.deviceMotion.magneticField.field.x;
    double y = motionManager.deviceMotion.magneticField.field.y;
    double z = motionManager.deviceMotion.magneticField.field.z;

    self.magnetometerDataLabel.text = [NSString stringWithFormat:@"{%8.4f, %8.4f, %8.4f}", x, y, z];
}];

Upvotes: 1

Related Questions