Core Motion

RSS for tag

Process accelerometer, gyroscope, pedometer, and environment-related events using Core Motion.

Posts under Core Motion tag

36 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

CoreMotion and movement WatchOS
Hello everyone, I'm coming to you because I'm having a little trouble finding the code to know the movement of the Apple Watch. I try to know exactly when the arm movement is up, down, left or right. I can define it thanks to “attitude.pitch” I can define it using "attitude", but it doesn't work correctly when the wrist is rotating at the same time as an arm movement. I no longer know how to move forward to know each movement. My code is as follows: (attitudeAvant11 is the attitude to the forward scan) (attitude11 is the attitude.pitch on the AppleWatch) Thank for your help func knowMove (attitude11:Double, attitudeAvant11:Double) -> (Sens2:String, attitudeAvant12:Double) { var attitude1 = attitude11 attitude1 = attitude1 * 100 let pourcentage = attitude1 - attitudeAvant if attitudeAvant != 0 { if pourcentage >= 0.5 { sensPrint = "Sens: Move down // ➡️\(pourcentage) ⬅️ // \(attitude1) // \(attitudeAvant)" sens1 = "1" } else { if pourcentage < -1.2 { sensPrint = "Sens: Move Up // ➡️\(pourcentage)⬅️ // \(attitude1) // \(attitudeAvant)" sens1 = "2" } else { sensPrint = "Sens: No Move // ➡️\(pourcentage)⬅️ // \(attitude1) // \(attitudeAvant)" sens1 = "0" } } } else { sensPrint = "Sens: No Move Initialisation // ➡️\(pourcentage)⬅️ // \(attitude1) // \(attitudeAvant) " } let DateMaintenant = Date() let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS" let dateString = formatter.string(from: DateMaintenant) if sens1 != "Nul" { TableauAttitude["\(dateString)"] = "\(sens1)" //print(TableauAttitude) } attitudeAvant = attitude1 print("sensPrint: \(sensPrint)") return (sens1,attitudeAvant) }
0
0
509
Dec ’23
recordAccelerometer
I am writing a code to capture the accelerometer data for one hour, it suppose to save in the iOS device first, and then I would like to upload to cloudkit. Here is my code. import UIKit import CoreMotion import CloudKit class ViewController: UIViewController { @IBOutlet weak var accelerometerSwitch: UISwitch! private let recorder = CMSensorRecorder() private let cloudKitContainer = CKContainer(identifier: "iCloud.com.example.accelerometer-recorder") override func viewDidLoad() { super.viewDidLoad() accelerometerSwitch.addTarget(self, action: #selector(accelerometerSwitchValueChanged), for: .valueChanged) } private func saveDataToAppFolder(data: [CMSensorRecordingData]) { let fileName = "accelerometer_data.dat" let fileManager = FileManager.default let documentsDirectoryURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first! let fileURL = documentsDirectoryURL.appendingPathComponent(fileName) let jsonData = try! JSONEncoder().encode(data) try! jsonData.write(to: fileURL) } @objc private func accelerometerSwitchValueChanged() { if accelerometerSwitch.isOn { recorder.recordAccelerometer(forDuration: 3600.0) { sensorData in if let sensorData = sensorData { // Handle the recorded data saveDataToAppFolder(data: sensorData) uploadDataToCloudKit(data: sensorData) } else { print("No accelerometer data recorded") } } } else { // No need to stop recording since it will stop automatically after the duration } } private func uploadDataToCloudKit(filePath: String) { let fileURL = URL(fileURLWithPath: filePath) let data = try! Data(contentsOf: fileURL) let record = CKRecord(recordType: "RecordedData") record["data"] = data let database = cloudKitContainer.publicCloudDatabase database.save(record, completionHandler: { record, error in if let error = error { print("Error uploading data to CloudKit: \(error)") } else { print("Data uploaded to CloudKit successfully") } }) } } Anyone can help to fix the error. Thanks a lot.
1
0
458
Nov ’23
Shallow Depth and Pressure entitlement
I wrote my app with the entitlement "com.apple.developer.submerged-shallow-depth-and-pressure" and also with underwater-depth for WKBackgroundMode. All is working fine when I tested the app. When I want to put the app in the store I got the following error: **Missing entitlement. The Info.plist for the watchOS app bundle at “Watch App.app” uses the underwater-depth value for WKBackgroundModes without the com.apple.developer.submerged-depth-and-pressure entitlement signed into the bundle. ** I wonder why the entitlement in the error message is without -shallow- and why I get this message.
2
0
767
Dec ’23
Issue Causing Auto-Reboots on iPhone 15 Pro/Pro Max
I recently stumbled upon a peculiar issue that's causing automatic reboots on the iPhone 15 Pro and iPhone 15 Pro Max. It appears that setting an extremely high value for gyroUpdateInterval can lead to this problem, but interestingly, the iPhone 15 doesn't exhibit the same behavior. Here's the code in question: - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { self.motionManager = CMMotionManager.new; self.motionManager.gyroUpdateInterval = 3600; // The problematic line [self.motionManager startGyroUpdatesToQueue:NSOperationQueue.mainQueue withHandler:^(CMGyroData * _Nullable gyroData, NSError * _Nullable error) { NSLog(@"Gyroscope data: %@", gyroData); }]; } It's worth noting that when I set gyroUpdateInterval to a more reasonable value like 60 (or omit it, as it uses a default value in that case), the reboots don't occur on the affected devices. I have tested this behavior on both the iPhone 15 Pro and the iPhone 15 Pro Max, and the issue is consistent on both devices. Surprisingly, the iPhone 15 does not seem to experience this problem. I'm eager to hear from other developers who might have encountered this issue or have insights into why setting an extreme gyroUpdateInterval could result in device instability on the iPhone 15 Pro and iPhone 15 Pro Max. This might be a device-specific quirk or potentially a bug in the Core Motion framework.
1
0
1.3k
Oct ’23
Core Motion on vision pro (specifically getting user's heading relative to north)
hi there, one thing i'm working on for the vision pro requires knowing the user's heading relative to north (magnetic or true). basically it's working with objects located using geo coordinates, and getting an angle of the direction the user is facing relative to them. on iOS and watchOS, i can use CMMotionManager's CMDeviceMotion heading property. looking at the docs it says this heading is there for visionOS, as is the xMagneticNorthZVertical reference frame.. however it seems like there is no magnetometer? it's a bit hard to tell in the simulator since isDeviceMotionAvailable, isAccelerometerAvailable and isGyroAvailable all return false. while isMagnetometerAvailable is a compile error (unavailable in visionOS). is there - or will there be - a way i can get the user's heading relative to north?
2
0
897
Oct ’23
Submerged Depth and Pressure entitlement
Following the information of accessing the Submerged and Depth and Pressure data (https://developer.apple.com/documentation/coremotion/accessing_submersion_data), I would like to get the Submerged Depth and Pressure entitlement. I went to Certificates, Identifiers & Profiles (https://developer.apple.com/account/resources/identifiers/list) I created an Identifire of Apple ID, Select App, the Capabilitiy of 'Shallow Depth and Pressure' turned true, put my app's bundle ID I created an Profile, select the Identifire I made ealier which have the Capability of 'Shallow Depth and Pressure' I went back to X-code, applied the profile I made earlier I woudl like to know whether I need to add the capability of 'Shallow Depth and Pressure' on X-code. I looked for the menu to add Capabillity on the X-code 'Signing & Capabiities' tab and '+ Capability' nemu, but 'Shallow Depth and Pressure' is not on the lists. If anyone could share your info to get Submerged Depth and Pressure entitlement successrully on X-code, it would be appreciated.
3
0
618
Sep ’23
Use CoreMotion in Landscape mode
Hello friends I’m currently developing an iOS application that uses the attitude from CoreMotion. For this I need to evaluate the specific values of Pitch, Roll and Yaw. As long as the app is in landscape mode and the device upright (X-axis up), I only need some small adjustments of the values to get the right attitude data. New: Pitch -> Y-axis, Yaw -> X-axis and Roll = Z-axis. func startDeviceMotion() { if motionManager.isAccelerometerAvailable { self.motionManager.deviceMotionUpdateInterval = self.interval self.motionManager.showsDeviceMovementDisplay = true self.motionManager.startDeviceMotionUpdates(using: .xTrueNorthZVertical) // Configure a timer to fetch the motion data self.timer = Timer(fire: Date(), interval: self.interval, repeats: true, block: { (timer) in if let motion = self.motionManager.deviceMotion { // write the values my own orientation data structure self.orientation.azimuthAngle = Measurement(value: -motion.attitude.yaw, unit: UnitAngle.radians) self.orientation.inclinationAngle = Measurement(value: -motion.attitude.roll-(Double.pi/2.0), unit: UnitAngle.radians) self.orientation.bankAngle = Measurement(value: motion.attitude.pitch, unit: UnitAngle.radians) } }) // Add the timer to the current run loop. RunLoop.current.add(self.timer!, forMode: RunLoop.Mode.default) } } However, when I use it in portrait mode (Y-axis up), I can't find a suitable conversion that provides me good values. Most of the time I get mixed values. The goal is that the following axes define Pitch, Roll and Yaw. Pitch -> X-axis, Yaw -> Y-axis, Roll -> Z-axis Has anyone ever had this problem and could explain how to get meaningful pitch, roll and yaw values with an iPad in portrait mode? Kind regards
0
0
470
Sep ’23
Shallow Depth and Pressure entitlement
Following https://developer.apple.com/documentation/coremotion/accessing_submersion_data I'm trying to "just get it started". I have a provisioning profile with the Shallow Depth and Pressure active, I have set the com.apple.developer.submerged-depth-and-pressure to true in the entitlements file, and get no errors or warning when compiling and starting the app on my Apple Watch Ultra. When my view appears, I init the submersion manager with the following code: guard CMWaterSubmersionManager.waterSubmersionAvailable else { return } submersionManager = CMWaterSubmersionManager() submersionManager?.delegate = self Logger.shared.info("SubmersionManager initialized") I get the printout SubmersionManager initialized, but then I get: An error occurred: The operation couldn’t be completed. (CMErrorDomain error 110.) Googling this error tells me this error means: CMErrorNotEntitled And I cannot find WHY the app is not entitled.. I find no information that this entitlement is not publicly available or anything.
3
0
1.1k
Jan ’24
CMMovementDisorderManager produces CMErrorUnknown
Hello, I am working on a clinical-grade application with access to the CMMovementDisorderManager API to track Parkinson's symptoms. Sometimes, these two method calls produce an NSError in the CMErrorDomain with code 103, which appears to be CMErrorUnknown: [CMMovementDisorderManager queryDyskineticSymptomFromDate:toDate:withHandler:] [CMMovementDisorderManager queryTremorFromDate:toDate:withHandler:] This is difficult for us to track down, because the error code is nondescript, and the user info is empty. We really don't have any clues as to what could be causing this behavior. I'm hoping a CoreMotion framework engineer with visibility into the code may be able to take a look and let us know what conditions can cause this result. Thanks! Dan
1
0
467
Aug ’23
How to use CMBatchedSensorManager
"for try await dataArray in bsm.deviceMotionUpdates()" generate error: Error Domain=CMErrorDomain Code=109 "(null)" Environment iOS 17.0 (21A5277j) watchOS 10.0 (21R5295g) XCode 15.0 beta 4 (15A5195m) Mac Studio 2022, macOS 13.4.1 (22F82) Details I create a swift project with code: File 1: let healthStore = HKHealthStore() var workoutSession: HKWorkoutSession! func workoutSession(_ workoutSession: HKWorkoutSession, didChangeTo toState: HKWorkoutSessionState, from fromState: HKWorkoutSessionState, date: Date) { } func workoutSession(_ workoutSession: HKWorkoutSession, didFailWithError error: Error) { } func requestAuthorization() { // The quantity type to write to the health store. let typesToShare: Set = [ HKQuantityType.workoutType() ] // The quantity types to read from the health store. let typesToRead: Set = [ HKQuantityType.quantityType(forIdentifier: .heartRate)!, HKQuantityType.quantityType(forIdentifier: .activeEnergyBurned)!, HKQuantityType.quantityType(forIdentifier: .distanceWalkingRunning)! ] // Request authorization for those quantity types healthStore.requestAuthorization(toShare: typesToShare, read: typesToRead) { success, error in // Handle error. } } // before call startWatch(), will request authorization to access Healthkit func startWatch(_ startWatchFor:Int) -> MotionManager? { let configuration = HKWorkoutConfiguration() let motionMgr: MotionManager? configuration.activityType = .golf configuration.locationType = .outdoor do { workoutSession = try HKWorkoutSession(healthStore: healthStore, configuration: configuration) workoutSession.startActivity(with: Date()) } catch { // Handle any exceptions. return nil } workoutSession.delegate = self ... // in turn, a func startUpdates() in another swift file will be called. } File 2: var batchedSensorManager: Any? @available(watchOSApplicationExtension 6.0.0, *) func batchedSensorUpdates() async { if #available(watchOSApplicationExtension 10.0, *), let bsm = batchedSensorManager as? CMBatchedSensorManager { bsm.startDeviceMotionUpdates() do { for try await dataArray in bsm.deviceMotionUpdates() { if !processDMEntry { break } ... // process data } } catch let error as NSError { print("batchedSensorManager.deviceMotionUpdates() fail", error.description) } } }
1
0
637
Jul ’23
Issue with accelerometerUpdates() function in CMBatchedSensorManager
I recently updated my iPhone to iOS 17.0 (21A5248v) and my Apple Watch Series 8 to watchOS 10.0 (21R5275t). I'm working with the CMBatchedSensorManager and have confirmed that the authorizationStatus is authorized. Additionally, both isDeviceMotionSupported and isAccelerometerSupported properties return true. However, when I call the startAccelerometerFetching() function shown below: @available(watchOS 10.0, *) func startAccelerometerFetching() async { do { for try await accelerometerList in batchedSensorManager.accelerometerUpdates() { accelerometerList.forEach { self.processAccelerometer($0) } } } catch let error as NSError { print("Encountered Error: \(error.userInfo) \(error.localizedDescription) -> \(error.code) \(error.localizedFailureReason)") } } I receive the following error message: "Encountered Error: [:] The operation couldn’t be completed. (CMErrorDomain error 109.) -> 109 nil" Does error code 109 correspond to CMErrorNotAvailable? How to solve this problem?
2
0
924
Aug ’23
CMMotionActivityManager reports inaccurate motion activity in iOS 16.4 Beta
Our App has a feature that needs to determine if the phone was stationary during the last 10 seconds. For the past several years, we have been using CMMotionActivityManager for this feature and it has worked very reliably. We query motion activity for the past 10 seconds (using queryActivityStarting(from:to:to:) method) and check for any events where the stationary property is false. However, the behavior of CMMotionActivityManager has changed in iOS 16.4 Beta: CMMotionActivityManager no longer reports motion as it did on iOS 16.3 and earlier versions. With iOS 16.4 Beta, CMMotionActivityManager will falsely return events where the stationary property is true (or return no events) even though the phone was in motion during the query interval. There are times when it does return motion events correctly, but that only happens if the phone is in constant motion for a sustained period of time. This behavior is drastically different from previous iOS versions where even the slightest bit of movement would generate motion events. i'm really hoping this is an issue in the beta and will be sorted out soon. Feedback Filed: FB12005598
2
1
1.2k
Aug ’23
Getting Raw Gyroscope Events not working in WatchOS 9.1
I was following the below documentation for getting the Raw Gyroscope events. Somehow I am unable to make the below code working. if motion.isGyroAvailable { self.motion.gyroUpdateInterval = 1.0 / 60.0 self.motion.startGyroUpdates() // Configure a timer to fetch the accelerometer data. self.acceTimer = Timer(fire: Date(), interval: (1.0/60.0), repeats: true, block: { (timer) in // Get the gyro data. if let data = self.motion.gyroData { let x = data.rotationRate.x let y = data.rotationRate.y let z = data.rotationRate.z // Use the gyroscope data in your app. print("rotationX: \(x) , rotationY: \(y) , rotationZ: \(z)") } }) // Add the timer to the current run loop. RunLoop.current.add(self.acceTimer!, forMode: .default) } https://developer.apple.com/documentation/coremotion/getting_raw_gyroscope_events The isGyroAvailable always returns false Dev environment - Xcode 14.1, Apple Watch 8, WatchOS 9.1
1
0
1.3k
Oct ’23
Core Ml Model, labels probabilities returning nan
Hi, I have a core ml model that when I try to print the: modelPrediction?.labelProbability which is of type String:Double and contains all the features with their corresponding probabilities, the value of type double comes with nan rest = nan right = nan up = nan Sometimes restarting makes it work again. Sometimes it can take a lot of restarts to start working again. Even when deleting the app and installing again the same thing happens. Also tried changing the deployment version but didn't seem to fix it. Any help is appreciated.
6
0
2.3k
Aug ’23