(El cálculo realizado aquí es una aproximación).
Los acelerómetros son dispositivos que miden la aceleración, que es la tasa de cambio de la velocidad de un objeto. Esto se mide en metros por segundo al cuadrado (m/s²) o en las fuerzas G (g). En el caso de iPhone se mide en fuerzas G.
ContenView.swift
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
import SwiftUI import CoreMotion struct SensorView: View { @State private var accelerationText = "Total Acceleration: 0.00 m/s²" @State private var forceText = "Force: 0.00 N" @State private var massText = "" @State private var previousMass: Float = 0.0 let motionManager = CMMotionManager() let gravity = 9.81 // Valor de la gravedad en m/s² var body: some View { VStack { Text(accelerationText) Text(forceText) TextField("Enter Mass", text: $massText) .textFieldStyle(RoundedBorderTextFieldStyle()) } .onAppear { startAccelerometer() } } func startAccelerometer() { if motionManager.isAccelerometerAvailable { motionManager.accelerometerUpdateInterval = 0.1 motionManager.startAccelerometerUpdates(to: .main) { [self] data, error in guard let acceleration = data?.acceleration else { return } let totalAccelerationG = sqrt(pow(acceleration.x, 2) + pow(acceleration.y, 2) + pow(acceleration.z, 2)) let totalAccelerationMS2 = totalAccelerationG * gravity // Convertir de g a m/s² accelerationText = String(format: "Total Acceleration: %.2f m/s²", totalAccelerationMS2) guard let mass = Float(massText) else { return } if mass != previousMass { forceText = "Force: 0.00 N" previousMass = mass } let force = calculateForce(acceleration: totalAccelerationMS2, mass: mass) if force > Float(forceText.components(separatedBy: " ")[1]) ?? 0 { forceText = String(format: "Force: %.2f N", force) } } } } func calculateForce(acceleration: Double, mass: Float) -> Float { return Float(acceleration * Double(mass)) } } struct SensorView_Previews: PreviewProvider { static var previews: some View { SensorView() } } |