Created
December 11, 2020 14:11
-
-
Save twissmueller/5a420b7a126cb4ce6de311e24753e971 to your computer and use it in GitHub Desktop.
Reading sensor values from iOS devices.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Combine | |
import CoreMotion | |
import Foundation | |
class MotionPublisher: ObservableObject { | |
@Published var accelerationX: Double = 0.0 | |
@Published var accelerationY: Double = 0.0 | |
@Published var accelerationZ: Double = 0.0 | |
@Published var rotationX: Double = 0.0 | |
@Published var rotationY: Double = 0.0 | |
@Published var rotationZ: Double = 0.0 | |
@Published var roll: Double = 0.0 | |
@Published var pitch: Double = 0.0 | |
@Published var yaw: Double = 0.0 | |
private var motionManager: CMMotionManager | |
public init() { | |
motionManager = CMMotionManager() | |
motionManager.startAccelerometerUpdates(to: .main) {accelerometerData, error in | |
guard let accelerometerData = accelerometerData else { return } | |
self.accelerationX = accelerometerData.acceleration.x | |
self.accelerationY = accelerometerData.acceleration.y | |
self.accelerationZ = accelerometerData.acceleration.z | |
} | |
motionManager.startGyroUpdates(to: .main) {gyroData, error in | |
guard let gyroData = gyroData else { return } | |
self.rotationX = gyroData.rotationRate.x | |
self.rotationY = gyroData.rotationRate.y | |
self.rotationZ = gyroData.rotationRate.z | |
} | |
motionManager.startDeviceMotionUpdates(to: .main) { (deviceMotion, error) in | |
guard let deviceMotion = deviceMotion else { return } | |
self.roll = deviceMotion.attitude.roll | |
self.pitch = deviceMotion.attitude.pitch | |
self.yaw = deviceMotion.attitude.yaw | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment