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 61 62 63 64 65 66 67 68 69 70 71 |
import SwiftUI import CoreMotion @main struct SensorApp: App { var body: some Scene { WindowGroup { SensorView() } } } 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) .padding() .background(Color.gray.opacity(0.2)) // Estilo de fondo para simular el borde .cornerRadius(8) // Borde redondeado } .onAppear { startAccelerometer() } } func startAccelerometer() { if motionManager.isAccelerometerAvailable { motionManager.accelerometerUpdateInterval = 0.1 motionManager.startAccelerometerUpdates(to: OperationQueue.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() } } |