let ALPHA = 0.5 let lastTiltX = 0 let lastTiltY = 0 let lastHeading = 0 let datosRegistro: number[][] = [] let registroActivo = false
input.calibrateCompass() basic.showString("OK")
function calcularInclinacion() { let x = input.acceleration(Dimension.X) let y = input.acceleration(Dimension.Y) let z = input.acceleration(Dimension.Z)
let tiltX = 0
let tiltY = 0
if (z != 0) {
tiltX = Math.atan2(x, z) * 57.3
tiltY = Math.atan2(y, z) * 57.3
} else {
tiltX = x > 0 ? 90 : -90
tiltY = y > 0 ? 90 : -90
}
tiltX = lastTiltX * ALPHA + tiltX * (1 - ALPHA)
tiltY = lastTiltY * ALPHA + tiltY * (1 - ALPHA)
lastTiltX = tiltX
lastTiltY = tiltY
return [tiltX, tiltY]
}
function calcularGiro() { let heading = input.compassHeading() let rotationChange = 0
if (lastHeading != 0) {
let diff = heading - lastHeading
if (diff > 180) {
diff -= 360
} else if (diff < -180) {
diff += 360
}
rotationChange = diff
}
lastHeading = heading
return rotationChange
}
function mostrarInclinacion(x: number, y: number) { let posX = 2 let posY = 2
if (y > 0) posX += Math.min(Math.floor(y / 20), 2)
if (y < 0) posX -= Math.min(Math.floor(-y / 20), 2)
if (x > 0) posY -= Math.min(Math.floor(x / 20), 2)
if (x < 0) posY += Math.min(Math.floor(-x / 20), 2)
basic.clearScreen()
led.plot(posX, posY)
}
function guardarDatos(tiltX: number, tiltY: number, rotation: number) { datosRegistro.push([input.runningTime(), tiltX, tiltY, rotation]) if (datosRegistro.length > 100) { datosRegistro.shift() // Mantener limitado a 100 registros } }
basic.forever(function () { let inclinacion = calcularInclinacion() let tiltX = inclinacion[0] let tiltY = inclinacion[1] let rotation = calcularGiro()
mostrarInclinacion(tiltX, tiltY)
if (registroActivo) {
guardarDatos(tiltX, tiltY, rotation)
}
basic.pause(100)
})
input.onButtonPressed(Button.A, function () { registroActivo = !registroActivo if (registroActivo) { datosRegistro = [] basic.showIcon(IconNames.Yes) } else { basic.showIcon(IconNames.No) } })
input.onButtonPressed(Button.B, function () { if (datosRegistro.length == 0) { basic.showString("No datos") return }
let maxTilt = 0
for (let i = 0; i < datosRegistro.length; i++) {
let tiltMag = Math.sqrt(datosRegistro[i][1] * datosRegistro[i][1] +
datosRegistro[i][2] * datosRegistro[i][2])
if (tiltMag > maxTilt) {
maxTilt = tiltMag
}
}
basic.showString("Max:" + Math.round(maxTilt))
basic.pause(500)
basic.showString("N:" + datosRegistro.length)
})
input.onButtonPressed(Button.AB, function () { basic.showString("Data") for (let i = 0; i < datosRegistro.length; i++) { serial.writeValue("t", datosRegistro[i][0]) serial.writeValue("x", datosRegistro[i][1]) serial.writeValue("y", datosRegistro[i][2]) serial.writeValue("r", datosRegistro[i][3]) basic.pause(10) } })