Search code examples
arraysswiftaccelerometer

Trying to capture accelerometer axis


When the button is pressed I'm trying to only capture the z data not the x and y. However, every time I try to add the .z to myData.acceleration {self.readings.append(myData.acceleration)} it wont let me. How would I be able to only capture the z data when the y hits a -39?

The error comes up saying:

Cannot convert value of type 'Double' to expected argument type 'CMAcceleration'

import UIKit
import CoreMotion

class ViewController: UIViewController {
    @IBOutlet var Count: UILabel!
    @IBOutlet var StartCount: UIButton!

    var motionManager = CMMotionManager()
    var count:String = "..."
    var counting:Bool = false
    var readings: [CMAcceleration] = []


    @IBAction func StartCount(_ sender: Any) {
        motionManager.startAccelerometerUpdates(to:OperationQueue.current!) {(data, error) in
            if let myData = data
            {
                if myData.acceleration.y < -39
                {
                    self.readings.append(myData.acceleration.z)
                }
                else
                {
                    self.Count.text = "GO!"
                }
            }
        }
    }
}

Might be a very basic quesstion but I cant figure it out.


Solution

  • You've declared your array to hold values of type CMAcceleration but you are trying to add just the z value which is a Double.

    If all you want in the array are the z values, change the array declaration to be an array of Double.

    var readings = [Double]()