【问题标题】:How to Properly Read Float Characteristic in Android Studio如何在 Android Studio 中正确读取浮点特性
【发布时间】:2020-05-31 03:31:55
【问题描述】:

我正在使用 ArduinoBLE 库来创建服务和特性:

BLEService angleService("1826");
BLEFloatCharacteristic pitchBLE("2A57", BLERead | BLENotify);

我添加服务和特性并宣传我的设备:

  BLE.setLocalName("acsAssist");
  BLE.setAdvertisedService(angleService);
  angleService.addCharacteristic(pitchBLE);
  BLE.addService(angleService);
  pitchBLE.writeValue(0);
  BLE.advertise();

我执行了一些计算,然后将我的计算值写入服务:

 pitchBLE.writeValue(posiPitch);

posiPitch 是一个浮点值,例如 1.96。它可以从 -90.00 到 90.00

我尝试从我的 Android 应用中读取此值:

(characteristic.getFloatValue(BluetoothGattCharacteristic.FORMAT_SFLOAT,0))

我得到了疯狂的数字,例如-1.10300006E9

如何读取我的浮点值,以便我的 android 应用程序值与 arduino 值匹配?

【问题讨论】:

    标签: android arduino bluetooth-lowenergy gatt bluetooth-gatt


    【解决方案1】:

    我遇到了类似的问题。我没有使用 getFloatValue(),而是使用了 getValue(),它返回一个字节数组。

    出现奇怪数字的原因是arduino存储数据的字节顺序与java不同。

    要更改顺序,请使用 byteBuffer:

    byte[] b = characteristic.getValue();
    float f = ByteBuffer.wrap(b).order(ByteOrder.LITTLE_ENDIAN).getFloat();
    

    这篇文章帮助了我:How to convert 4 bytes array to float in java

    【讨论】:

      【解决方案2】:

      我通过使用字符串特性大大简化了这种情况。

      虽然这可能更耗费资源,但它减少了必须解析字节数组以将数据转换为我想要的数据的麻烦。

      我的字符串特征是使用自定义 UUID 制作的(以避免蓝牙 GATT 标准冲突):

      BLEStringCharacteristic pitchBLE("78c5307a-6715-4040-bd50-d64db33e2e9e", BLERead | BLENotify, 20);
      

      在我做广告并按照我原来的帖子所示执行计算之后,我只需写入我的特征并将值作为字符串传递:

      pitchBLE.writeValue(String(posiPitch));
      

      在我的 Android 应用程序中,我只需获取特征的字符串值:

      characteristic.getStringValue(0)
      

      我希望这将有助于像我这样正在努力寻找更清晰的信息资源的未来开发人员:)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-05-22
        • 1970-01-01
        • 2010-09-24
        • 1970-01-01
        相关资源
        最近更新 更多