根据Kotlin的Android手机计算位置,依靠小动作来模拟蝴蝶网

在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