motionpotion
motionpotion

Reputation: 2736

How To Measure Amount Of Shake On iOS Device In Swift?

I'm using CoreMotion to acquire device motion measurements in an app. I can get acceleration x y z, roll, pitch, yaw, gyro data, etc.

But what I'm trying to measure is shake i.e. how much the device is moving and to set thresholds for when a device has moved a large amount in any direction. I've found that the measurements I'm getting back are super sensitive and I don't know how to use it all correctly.

Note: I know about detecting the shake gesture and that is not what I'm asking - I'm asking for the correct way to measure the amount of shake and display it.

Sample of code I'm using from DeviceMotion:

        if let deviceMotion = motionManager.deviceMotion {
        let quat = deviceMotion.attitude.quaternion;
        var qRoll = radiansToDegrees(radians: atan2(2*(quat.y*quat.w - quat.x*quat.z), 1 - 2*quat.y*quat.y - 2*quat.z*quat.z)) ;
        var qPitch = radiansToDegrees(radians: atan2(2*(quat.x*quat.w + quat.y*quat.z), 1 - 2*quat.x*quat.x - 2*quat.z*quat.z));
        var qYaw = radiansToDegrees(radians: asin(2*quat.x*quat.y + 2*quat.w*quat.z));

        let orientation = deviceMotion.attitude
        var roll = radiansToDegrees(radians: orientation.roll)
        var pitch = radiansToDegrees(radians: orientation.pitch)
        var yaw = radiansToDegrees(radians: orientation.yaw)
}

And using accelerometer:

        if motionManager.isAccelerometerAvailable {
        motionManager.startAccelerometerUpdates(to: OperationQueue.current!, withHandler: { accelerometerData, error in
            if let acceleration = accelerometerData?.acceleration {
                print("ACCELEROMETER X: " + acceleration.x.description)
                print("ACCELEROMETER Y: " + acceleration.y.description)
                print("ACCELEROMETER Z: " + acceleration.z.description)
        })
    }

What is the correct way to use the measurements from CoreMotion to measure how much a device is shaking?

Upvotes: 2

Views: 997

Answers (1)

nathangitter
nathangitter

Reputation: 9795

It depends on your exact use case, but if you want to determine the amount of shake, calculate a motion delta. Determine the maximum and minimum values for one of the device motion attributes within a given period of time, and use that value as an approximation of "shakiness".

For example, you could measure the yaw of the device over a period of 5 seconds. Keep track of the minimum and maximum values, and take the difference between them. More shaking will result in a larger value.

Again it depends on your exact use case, but you could also take a combination of device motion attributes and their motion deltas. If you knew that the motion was consistent over time (like a machine shaking back and forth), you could try to find local min/max values and average them over a period of time.

Upvotes: 2

Related Questions