在Kotlin中计算Android手机的小动作位置,以模拟蝴蝶网

Jam*_*ack 13 android accelerometer

在Kotlin,我正在开发一个程序,用户可以移动手机来控制虚拟蝴蝶网.位置信息被发送到MQTT broker,UI应用程序将获取数据.

我的问题是准确地显示了这个位置.如果手机是捕手的净部分,那么理想情况下,当您移动手机时,使用加速度计我应该知道您正在移动哪个方向,并且可以发送该数据.

理论上很好,在实践中更难.

为了减少代码,我只想知道手机向上移动多少,意识到它最多会向上移动两到三英尺,所以如果移动六英寸,我想告诉用户界面向上移动六英寸.

我想在开始部分根据手机的方向进行调整.

如何准确跟踪位置信息?

override fun onSensorChanged(sensorEvent: SensorEvent?) {
    val mySensor = sensorEvent!!.sensor

     if (mySensor.type == Sensor.TYPE_ACCELEROMETER) {
        var mSensorZ: Float= 0F
        when (mDisplay?.getRotation()) {
            Surface.ROTATION_0 -> {
                mSensorZ = sensorEvent.values[2];
            }
            Surface.ROTATION_90 -> {
                mSensorZ = sensorEvent.values[2];
            }
            Surface.ROTATION_180 -> {
                mSensorZ = sensorEvent.values[2];
            }
            Surface.ROTATION_270 -> {
                mSensorZ = sensorEvent.values[2];
            }
        }
         val alpha = 0.8;

        var gravity = DoubleArray(3)
        var linear_acceleration = DoubleArray(3)
        // Isolate the force of gravity with the low-pass filter.
        gravity[2] = alpha * gravity[2] + (1 - alpha) * sensorEvent.values[2];

        // Remove the gravity contribution with the high-pass filter.
        linear_acceleration[2] = sensorEvent.values[2] - gravity[2];
        // Limit to 3 significant figures, rather than using BigDecimal
        val nz = (((mSensorZ - gravity[2]) * 1000).toInt() / 1000).toFloat()
        if(Math.abs(lz - nz) > 0.3) {
            Log.d(TAG, "Moved z " + (lz - nz))
            // This may be the wrong direction, don't care as long as it is roughly accurate on amount 
            val payload: String = if (lx1 - nz < 0) Operator.Right.toString() + (12 * (lz1 - nz)).toString() else Operator.Up.toString() + (12 * (lz1 - nz)).toString
            try {
                val encodedPayload = payload.toByteArray(Charset.defaultCharset())
                val message = MqttMessage(encodedPayload)
                val r = client?.publish(topic, message);
                Log.d(TAG, "**** mqtt: ${payload}")
            } catch (e: Exception) {
                e.printStackTrace();
            }

        }
        lz = nz
Run Code Online (Sandbox Code Playgroud)

Gle*_*des 0

我想你应该使用 Sensor.TYPE_LINEAR_ACCELERATION 来处理消除重力。这将为您提供准确的值。还可以尝试使用任何具有世界值映射的统一插件,它将正确映射到您的计算值。