In yesterday’s Daily Coding Tip I made use of raw gyroscope data in order to move a Circle
around on the screen. As I said in that tutorial, the accelerometer detects changes in acceleration such as shaking your phone, while the gyroscope detects how much the device has been rotated. Apple doesn’t actually recommend using the raw output from the gyroscope, stating this in the documentation:
The raw rotation rate data delivered by the gyroscope interfaces may be biased by other factors such as device acceleration. If your app requires unbiased rotation values, use the device-motion interfaces instead. The device-motion interfaces use special algorithms to remove any bias and deliver more precise rotation values.
This time I’m going to be using the device-motion interfaces, and you’ll be able to tell that the data we get is a lot more reliable.
Please note that making use of the gyroscope requires that the UIRequiredDeviceCapabilities
key is added to your info.plist, which will be displayed as an array. You will then need to add a string value to this array called gyroscope in order to use that capability.
Here’s what I’m doing in GyroViewModel
this time:
There are a lot of similarities here. Instead of startGyroUpdates
here I’m calling startDeviceMotionUpdates
, but both functions are inherited from the CMMotionManager
class. Instead of x
, y
and z
values we are getting pitch
, roll
and yaw
, but they amount to the same thing. These are then checked 60 times per second when a Timer
fires, exactly the same as they were for raw gyroscope data.
The user interface is actually exactly the same as yesterday’s Daily Coding Tip, as all of the changes occur in the GyroViewModel
.
It should be pretty obvious from the motion of the Circle
that this version of the data is a lot less erratic, which is an improvement over the raw gyroscope data used previoiusly.