Let's say the iPhone is placed on a flat table. I would like to determine the angle of the plane of the table, where the angle 0 means that the table is exactly perpendicular to the gravity vector. I use the following formula:
radians = atanf (z / sqrt (x^2 + y^2)
in .h
double accelerationXAverage;
double accelerationYAverage;
double accelerationZAverage;
double accelerationXSum;
double accelerationYSum;
double accelerationZSum;
int readingsCount;
in .m
#define kThresholdMovementHigh 0.05
- (void)accelerometer:(UIAccelerometer *)accelerometer
didAccelerate:(UIAcceleration *)acceleration
{
if (fabsf(acceleration.x - accelerationXAverage) > kThresholdMovementHigh ||
fabsf(acceleration.y - accelerationYAverage) > kThresholdMovementHigh ||
fabsf(acceleration.z - accelerationZAverage) > kThresholdMovementHigh )
{
NSLog(@"deviceDidMove a lot");
accelerationXSum = acceleration.x;
accelerationYSum = acceleration.y;
accelerationZSum = acceleration.z;
readingsCount = 1;
}
else
{
accelerationXSum += acceleration.x;
accelerationYSum += acceleration.y;
accelerationZSum += acceleration.z;
readingsCount ++;
}
accelerationXAverage = accelerationXSum / readingsCount;
accelerationYAverage = accelerationYSum / readingsCount;
accelerationZAverage = accelerationZSum / readingsCount;
float angle = RadiansToDegrees(atanf(accelerationZAverage/sqrtf(pow(accelerationXAverage, 2) + pow(accelerationYAverage, 2)))) + 90;
labelAngle.text = [NSString stringWithFormat:@"%.2f°", angle];
}
I filter noise by averaging accelerometer readings. The accelerometer update interval is 1/60, and while you are experimenting, I let the device sit for 10 seconds (so it averages 600 samples).
, , , , . , , , , , ( , ), , , . .
? ? ?
( http://gotoandplay.freeblog.hu/), , x- y- z. 