Skip to content

Instantly share code, notes, and snippets.

@sturdysturge
Created January 16, 2023 20:11
Show Gist options
  • Select an option

  • Save sturdysturge/d565d6f652bdac4e405cbb24e42d2d70 to your computer and use it in GitHub Desktop.

Select an option

Save sturdysturge/d565d6f652bdac4e405cbb24e42d2d70 to your computer and use it in GitHub Desktop.
import CoreMotion
class GyroViewModel: CMMotionManager, ObservableObject {
var timer = Timer()
@Published var x: Double = 0
@Published var y: Double = 0
@Published var z: Double = 0
func start() {
if isDeviceMotionAvailable {
deviceMotionUpdateInterval = 1.0 / 60.0
showsDeviceMovementDisplay = true
startDeviceMotionUpdates(using: .xMagneticNorthZVertical)
self.timer = Timer(fire: Date(),
interval: (1.0 / 60.0),
repeats: true) { (timer) in
self.x = self.deviceMotion?.attitude.pitch ?? 0
self.y = self.deviceMotion?.attitude.roll ?? 0
self.z = self.deviceMotion?.attitude.yaw ?? 0
}
RunLoop.current.add(self.timer, forMode: RunLoop.Mode.default)
}
}
func stop() {
timer.invalidate()
stopDeviceMotionUpdates()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment