ThisDarkTao
ThisDarkTao

Reputation: 1062

Detecting that the device moved

I am creating a motion detection alarm for the iPhone. This alarm will be set by pressing an 'Activate' button, and after a small countdown, will then take readings about whether it is moving. I have tried using the accelerometer to detect movement, but if the threshold becomes too low it activates constantly, whether the device is moving or not. If I set the threshold higher it does not detect movement, and will only detect specific speeds of motion.

Does anyone have any solutions as to how to do this correctly, not by an amount of force, but whether the phone has actually moved.

I have tried to find online examples of how to implement it but only came up with solutions for augmented reality and OpenGL etc. All I need is a simple detection of motion.

Thank you for any help!

EDIT:

I managed to get it working using some samples from the Apple documentation.

I've managed to achieve what I want using this accelerometer didAccelerate method:

- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {
    // Use a basic low-pass filter to keep only the gravity component of each axis.
    accelX = (acceleration.x * kFilteringFactor) + (accelX * (1.0 - kFilteringFactor));
    accelY = (acceleration.y * kFilteringFactor) + (accelY * (1.0 - kFilteringFactor));
    accelZ = (acceleration.z * kFilteringFactor) + (accelZ * (1.0 - kFilteringFactor));

    float accelerationThreshold = 1.01; // or whatever is appropriate - play around with different values

    if (fabs(accelX) > accelerationThreshold || fabs(accelY) > accelerationThreshold || fabs(accelZ) > accelerationThreshold) {
        [self.soundPlayer play];
        accelX = accelY = accelZ = 0;
        accelerometerActive = NO;
        accelerometer.delegate = nil;
        accelerometer = nil;
    }
}

Upvotes: 2

Views: 2009

Answers (1)

Rob Forrest
Rob Forrest

Reputation: 7450

One way to do this could be to calculate a vector for gravity. If the phone isn't moving then the vector will remain fairly constant. Should the phone be picked up it is likely that the orientation of the phone will change, thus the gravity vector will also change (in relation to the orientation of the accelerometer).

To detect movement simply calculate the angle between the original vector set on 'Activate' and the current vector. Googling angles between 3d vectors will help you out with the mathmatics behind this.

Theoretically someone could pick the phone up and maintain the exact orientation but this is incredibly unlikely.

Hope this helps and good luck.

Upvotes: 3

Related Questions