Yesterday we created a very simple tutorial that let you enable the accelerometer on your device. Today, we’ll look at how to access the gyroscope through the CMMotionManager. These early tutorials are only a very small part of what Core Motion offers, but act as a starting point to show you the very basics of how to get access to the various sensors that Apple has placed in the iPhone.
In later tutorials we’ll look at other aspects of Core Motion and provide some examples of how you might use Core Motion within your own app.
Enabling Gyroscope Updates
The code to enable the gyroscope is very simple. You first need to import Core Motion as follows:
import CoreMotion
In viewDidLoad, add the following:
if motionManager.isGyroAvailable { motionManager.gyroUpdateInterval = 0.1 motionManager.startGyroUpdates(to: OperationQueue.main) { (data, error) in print(data) } }
On line 1 we check if the gyroscope is available.
Line 2 we set the update interval. 0.1 is 10 times per second. You will be able to receive updates faster than that if your app needs it, so adjust this value to get the refresh rate you desire. If timing is important to your app, then Apple suggests you check the timestamp and adapt as necessary.
Line 3 we start the gyro updates. The gyro is actually already running and always is while your phone is powered on, but what we are doing here is saying that our app is interested in receiving this data. We push the updates to the main operation queue and in this example, we also use a handler which returns the data and an error if needed. There is a different version of the startGyroUpdates method. That particular version does not have an update handler. Instead, you call gyroData on the motion manager if you want to capture the gyro values for that particular moment.
Line 4 is just used to print out the data which shows CMGyroData.
This is pretty much all that is needed to receive data from the gyroscope on the device. Actually making that data useful is the real challenge, and one that will be addressed in another tutorial.
Leave a Reply
You must be logged in to post a comment.