## Accelerometer implementation

Hello again!

Hi! In this tutorial I’m going to show you how simple can be accelerometer implementation in our App. It’s a piece of cake!

So let’s go.

@interface AccelerometerViewController : UIViewController

2. In the same file you need to write a header of function which will be receiving the accelerometer values:

– (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *) acceleration;

3. Next you should prepare the accelerometer for example in viewDidLoad or initWithCoder:

[[UIAccelerometer sharedAccelerometer] setUpdateInterval:(1.0/30.0f)];
[[UIAccelerometer sharedAccelerometer] setDelegate:self];

In setUpdateInterval you can change the accelerometer update frequency but remember, too high can makes your app runs slower!

4. Now let’s take a look at our accelerometer function:

– (void) accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *) acceleration {
float x = [acceleration x];
float y = [acceleration y];
float z = [acceleration z];
}

Here is the picture for you of the iPhone axes from Apple Site: But I must say about one important thing. If you want to use accelerometer in your apps you can’t do something like this:

MyObj.x += [acceleration x];

Even when you think that your hands are not shaking you are wrong.
The iphone accelerometer is very precise so your Object will be shaking in an ugly way. You need to change you objects status just when the axes are changed by a set interval.

So you need to do something like this:

float tempAngle = 0; // do this when your app starts.

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

float x = [acceleration x];

if ((x – tempAngle > 0.05) || (x – tempAngle < -0.05))
{
temp_angle = x;
MyObj.x += x;
}

}

The |0.05| + |-0.05| value is your interval.

I hope it will be helpful!