IPhone Screen Orientation

I want to determine the orientation of the iPhone in increments of 45 degrees. Ideally, I would like to get an orientation angle along any axis.

The detection I need to do is similar to the way Trism for iPhone flashes an arrow in the direction of the current bottom position of the screen when the orientation changes.

I have something encoded, but I don’t really understand how the accelerometer readings work, and you can use the boost in the right direction. My current code registers the current angle, but even when the phone is flat, I get readings that change several times per second.

- (void) checkOrientation:(UIAccelerometer*)accelerometer didAccelerate:(UIAcceleration*)acceleration { int accelerationX = acceleration.x * kfilteringFactor + accelerationX * (1.0 - kfilteringFactor); int accelerationY = acceleration.y * kfilteringFactor + accelerationY * (1.0 - kfilteringFactor); float currentRawReading = (atan2(accelerationY, accelerationX)) * 180/M_PI; NSLog(@"Angle: %f",currentRawReading); } 

Example from the log when the phone is flat:

 2009-06-16 17:29:07.987 [373:207] Angle: 0.162292 2009-06-16 17:29:07.994 [373:207] Angle: 179.838547 2009-06-16 17:29:08.014 [373:207] Angle: 179.836182 2009-06-16 17:29:08.032 [373:207] Angle: -90.000000 2009-06-16 17:29:08.046 [373:207] Angle: 179.890900 2009-06-16 17:29:08.059 [373:207] Angle: -90.000000 2009-06-16 17:29:08.074 [373:207] Angle: 179.917908 2009-06-16 17:29:08.088 [373:207] Angle: -179.950424 2009-06-16 17:29:08.106 [373:207] Angle: 90.000000 2009-06-16 17:29:08.119 [373:207] Angle: 90.000000 2009-06-16 17:29:08.134 [373:207] Angle: -179.720245 
+5
source share
2 answers

I think your problem is that you use int variables if you want a float .

I think that accelerationX and -Y should be instance variables and thus:

 accelerationX = acceleration.x * kfilteringFactor + accelerationX * (1.0 - kfilteringFactor); accelerationY = acceleration.y * kfilteringFactor + accelerationY * (1.0 - kfilteringFactor); 

Should give you more of what you were looking for.

+4
source

The reason is because you are using local variables, while they should not be local.

Try the following:

Declare instance variables:

 @interface YourViewControllerClass: UIViewController { float accelerationX, accelerationY; } ... other declarations 

Update variables in accelerometer delegate:

  accelerationX = acceleration.x * kfilteringFactor + accelerationX * (1.0 - kfilteringFactor); accelerationY = acceleration.y * kfilteringFactor + accelerationY * (1.0 - kfilteringFactor); 

It should give more accurate results without sudden jumps.

+3
source

All Articles