Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to detect motion of iPhone 6 device? (determine whether iPhone device moved or not -smallest possible motion on x,y,z- )

I'm working on a task to determine when the iPhone 6 is moving (smallest possible move not even a shake!) at any direction (x,y or Z) . what is the best way to achieve that?

like image 299
Alaa Avatar asked Nov 01 '25 15:11

Alaa


1 Answers

I used this code and found it useful, it contains four functions : - Start motion manager - Stop motion manager - Update motion manager - magnitudeFromAttitude

import CoreMotion
let motionManager: CMMotionManager = CMMotionManager()
var initialAttitude : CMAttitude!

//start motion manager
func StartMotionManager () {
    if !motionManager.deviceMotionActive {
        motionManager.deviceMotionUpdateInterval = 1
    motionManager.startDeviceMotionUpdates()
    }
}
//stop motion manager
func stopMotionManager ()
{
    if motionManager.deviceMotionActive
    {
 motionManager.stopDeviceMotionUpdates()
    }
}

//update motion manager
func updateMotionManager (var x : UIViewController) 
{

    if motionManager.deviceMotionAvailable {
        //sleep(2)
        initialAttitude  = motionManager.deviceMotion.attitude
        motionManager.startDeviceMotionUpdatesToQueue(NSOperationQueue.currentQueue(), withHandler:{
            [weak x] (data: CMDeviceMotion!, error: NSError!) in

            data.attitude.multiplyByInverseOfAttitude(initialAttitude)

            // calculate magnitude of the change from our initial attitude
            let magnitude = magnitudeFromAttitude(data.attitude) ?? 0
            let initMagnitude = magnitudeFromAttitude(initialAttitude) ?? 0

            if magnitude > 0.1 // threshold
            {
                // Device has moved ! 
               // put the code which should fire upon device moving write here

                initialAttitude  = motionManager.deviceMotion.attitude
            }
                       })

        println(motionManager.deviceMotionActive) // print false
    }

}


// get magnitude of vector via Pythagorean theorem
func magnitudeFromAttitude(attitude: CMAttitude) -> Double {
    return sqrt(pow(attitude.roll, 2) + pow(attitude.yaw, 2) + pow(attitude.pitch, 2))
}
like image 185
Alaa Avatar answered Nov 03 '25 12:11

Alaa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!