Getting Accelerometer data

Now, in our ViewController.swift file we're going to create a function that will give us our accelerometer data. Here's the function that I've created:

func startAccelerometerX () {
        motionManager.accelerometerUpdateInterval = 2.5
        motionManager.startAccelerometerUpdates(to: OperationQueue.current!, withHandler: {
            (accelerData:CMAccelerometerData?, error: Error?) in
            if (error != nil ) {
            } else {
                let accelX = accelerData?.acceleration.x
                self.accelTagX.text = String(format: "%.02f", accelX!)                
                print("Accelerometer X: \(accelX!)")

First, we'll create a function called startAccelerometerX. Within our function we'll call theaccelerometerUpdateInterval method to receive updates of the accelerometer's current x-axis position in intervals of the time we choose.

Here, we'll set the interval time to 2.5 seconds:

motionManager.accelerometerUpdateInterval = 2.5

Next, we'll start acceleration updates with the startAccelerometerUpdate method. This method starts accelerometer updates on an operation queue with a specified handler.

motionManager.startAccelerometerUpdates(to: OperationQueue.current!, withHandler: {}

Within the handler, if we run into an error, the string "error" will be printed in the console. If we don't encounter an error, we'll run the else statement where we'll create a constant called accelX and give it the value of the acceleration data on the x-axis:

 let accelX = accelerData?.acceleration.x

Now that we have our accelerometer data, we'll give our accelTagX label the accelX value so that our label will display our accelerometer data.

self.accelTagX.text = String(format: "%.02f", accelX!)

Now we are going to create a new function that stops the startAccelerometerX function from updating.

Create a new function, and call it stopAccelerometerX. This one is pretty straightforward, we'll call the stopAccelerometerUpdates method to stop accelerometer updates. Then we're going to change the accelTagX label to "--".

    func stopAccelerometerX () {
        self.accelTagX.text = "--"
        print("Accelerometer X Stopped")

Ok, let's test it out. In theviewDidLoad function lets call our startAccelerometerX function to make sure everything is running as it should.

    override func viewDidLoad() {

Hit the Build button to run your app. If everything runs smoothly, the app should launch on your iOS device.  As you turn your device, you should see the accelX label display your iOS accelerometer data as your device tilts.

If your label is not updating, try going through the guide again or look at the IO Connect Example app.

Next, we are going to send our accelX data to Adafruit IO using the REST "POST" method.

Last updated on 2017-12-31 at 01.12.22 PM Published on 2018-01-01 at 10.39.04 PM