0

How do I have to use the accelerometer / gyroscope in objective-c in order to find out if...

A) the iPhone is held just in front of the users face, i.e. it is held "upwards" or

B) the iPhone has been put for instance on a table, i.e. the display is facing up.

Chris Pfohl
  • 18,220
  • 9
  • 68
  • 111
itsame69
  • 1,540
  • 5
  • 17
  • 37

4 Answers4

5

You need to read the UIAcceleration Class Reference and note that gravity is always present. Thus when the iPhone is vertical (and held steady) you will read 1g along the y-axis. When it is flat on the table you will read 1g along the z-axis

Peter M
  • 7,309
  • 3
  • 50
  • 91
1

Firstly conform to <UIAccelerometerDelegate> and then you can use these methods:

    #pragma mark --- Acceleration Start and Stop ----------------------------

    -(void)startMeasuringAcceleration{

        NSLog(@"Started Measuring Acceleration");

        [[UIAccelerometer sharedAccelerometer] setUpdateInterval:1];//update interval (1s at moment)
        [[UIAccelerometer sharedAccelerometer] setDelegate:self];

    }

    -(void)stopMeasuringAcceleration{

        [[UIAccelerometer sharedAccelerometer] setDelegate:nil];

    }

    #pragma mark UIAcceleromete Delegate Methods-----------------------------------------------

    - (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration{

        NSLog(@"%f, %f, %f, %f", acceleration.x, acceleration.y, acceleration.z, acceleration.timestamp);

}

Measure X, Y and Z. Z is the axis on the screen, Y top to bottom and X left to right.

In viewDidLoad call [self startMeasuringAcceleration] to start

Hope that helps.

Adam Waite
  • 19,175
  • 22
  • 126
  • 148
  • Thanks a lot, Adam! In combination with Peters answer (see below), this is exactly what I was looking for! PS: As I am only able to mark one answer as "accepted answer" I vote for yours because of the example source code. However, also Peter should get some credits ;-) – itsame69 Nov 28 '12 at 19:30
  • No problem. Happy to help (as Stack Overflow does to me so often!). – Adam Waite Nov 28 '12 at 19:42
0

You need to read the z coordinate value of the accelerometer.

cem
  • 3,311
  • 1
  • 18
  • 23
  • That should be Z, X is on the plane as if you were looking at the device screen and swaying your arm left to right. – Adam Waite Nov 29 '12 at 07:30
0

You should not use UIAccelerometerDelegate as it is deprecated since iOS 5.0. Starting with iOS 4 this was replaced by the far more reliable Core Motion framework which uses sensor fusion.

So have a look at:

Why is accelerometer:didAccelerate: deprecated in IOS5?

Simple iPhone motion detect

Follow the links inside to the Apple docs

Community
  • 1
  • 1
Kay
  • 12,918
  • 4
  • 55
  • 77