Search code examples
objective-ciosaccelerometer

How to get force exercised on Accelerometer axis at a particular "moment"?


I'm rather new to Objective-C and iOS development, and after having read some of the documentation on the Accelerometer class I'm still not sure about a few things so maybe you can clarify these for me.. Also please excuse my C++.. I'm only using it as an example..

I want to create a while-loop that looks smith like this:

while(play)
{
    while(getYaxis()>=..... && getYaxis()<=....)
    {
        //do something..
    }
    //more code to execute...
}

I want to create a method called "getYaxis" that returns the force exercised on the Y-axis of the accelerometer at the moment the method is called...

Is this possible and how? Apparently you can set the Accelerometer to return g values at regular intervals, where as I only want to have a single value returned the "second" I ask for it in my while-condition. Then the rest of the code should be executed as shown above and at some point I will return to that while-loop and check the Y-value again. In other words, rather than setting an interval regarding how often to check the accelerometer value, I want to let that interval be the time it takes to execute the rest of the code and come back to the while loop that will be checking the Y-value again.. Or is this interval between the two checks so short that could cause problems eventually?

Thanks!


Solution

  • Here is how you get the Accelerometer and become the delegate:

    UIAccelerometer *theAccelerometer = [UIAccelerometer sharedAccelerometer];
    theAccelerometer.updateInterval = 0.001; //in seconds
    theAccelerometer.delegate = self;
    

    Remember to add <UIAccelerometerDelegate> to your VC.

    Then you can catch the changes in:

    -(void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration
    
    {
        self.x = acceleration.x;
        self.y = acceleration.y;
        self.z = acceleration.z;
    }
    

    Make sure you have properties created for x,y,z of the type UIAccelerationValue.

    Then just write a method called getX or getY;

    -(UIAccelerationValue *) getY
    {
        return self.y;
    }
    

    You will have it updating very millisecond or however fast you want, and saving it in a property. Then you can check the property's value with the function.