Search code examples
objective-ciosaccelerometer

How do I compare a constant value to a continuously-updated Accelerometer value each time round a loop?


As it was suggested to me in a previous post of mine, the following code takes the data coming from the accelerometer the "minute" the assignment : CMAccelerometerData* data = [manager accelerometerData]; is performed, and then extracts from that data the acceleration exercised on the x-Axis and stores its value in a double (double x) :

 CMMotionManager* manager = [[CMMotionManager alloc] init];

 CMAccelerometerData* data = [manager accelerometerData];

 double x = [data acceleration].x;

Suppose the value stored is 0.03 and suppose that I want to use it in a while loop as follows :

while (x > 0)
{
    // do something
}

the above loop will obviously run forever

However, what if I used the following code instead :

CMMotionManager* manager = [[CMMotionManager alloc] init];

while([[manager accelerometerData] acceleration].x > 0) 
{
    // do something
}

wouldn't I be now comparing zero to a different value each time round the loop? (which is what I'm going for in my project anyway..)

any thoughts?

the reason I'm asking this is the following :

I want to check the values coming from the x-Axis over a certain period of time, rather than keep checking them at regular intervals, so I basically want to write a loop that would look something like this :

if ([[manager accelerometerData] acceleration].x > 0 ) 
{
    // initialiseTimer
}

while ([[manager accelerometerData] acceleration].x > 0 ) 
{
    if( checkTimer >=250ms )
    {
        stopTimer;

        printOut("X-Axis acceleration  was greater than zero for at least 250ms");

        breakFromLoop;
     }
}

I know the code in my 2nd if-block isn't valid Objective-C..This was just to give you an idea of what I'm going for..


Solution

  • This has a simple solution.

    1)Declare an instance variable x that you update each time the accelerometer tell you to.

    2)Compare this x to whatever value you need in the loop .

    Hope this helps.

    Regards,

    George