我正在使用ArduinoBLE库创建服务和特征:
-1
我添加服务和特征并宣传我的设备:
Collection
我先进行一些计算,然后将计算出的值写入服务:
private final List<Integer> invocations = new ArrayList<>();
public int newNumber(final int i) {
if (!this.invocations.contains(i)) {
// Not seen before, so add to the List, and return -1.
this.invocations.add(i);
return -1;
}
// size - 1 for 0 indexed list.
// - last index of it since that was the last time it was called.
final int lastInvocation
= this.invocations.size() - 1 - this.invocations.lastIndexOf(i);
// Remove all prior occurrences of it in the List.
// Not strictly necessary, but stops the List just growing all the time.
this.invocations.removeIf(value -> value.equals(i));
// Add the element as the latest invocation (head of the List)
this.invocations.add(i);
return lastInvocation;
}
BLEService angleService("1826");
BLEFloatCharacteristic pitchBLE("2A57", BLERead | BLENotify);
是一个浮点值,例如1.96。它可以从-90.00到90.00
我尝试从我的Android应用读取此值:
BLE.setLocalName("acsAssist");
BLE.setAdvertisedService(angleService);
angleService.addCharacteristic(pitchBLE);
BLE.addService(angleService);
pitchBLE.writeValue(0);
BLE.advertise();
我得到疯狂的数字,例如 pitchBLE.writeValue(posiPitch);
。
如何读取我的float值,以便我的android应用程序值与arduino值相匹配?
答案 0 :(得分:0)
我通过利用字符串特性极大地简化了这种情况。
尽管这可能会占用更多资源,但它减轻了必须解析字节数组以将数据转换为所需内容的麻烦。
我的字符串特征是使用自定义UUID制作的(以避免Bluetooth GATT标准冲突):
BLEStringCharacteristic pitchBLE("78c5307a-6715-4040-bd50-d64db33e2e9e", BLERead | BLENotify, 20);
按照我的原始帖子中所示做广告并执行计算后,我只需写我的特征并将值作为字符串传递:
pitchBLE.writeValue(String(posiPitch));
在我的Android应用程序中,我只是获得特征的字符串值:
characteristic.getStringValue(0)
我希望这将有助于像我这样的未来开发人员,他们正在努力寻找有关此类信息的更清晰资源:)
答案 1 :(得分:0)
我遇到了类似的问题。我没有使用 getFloatValue(),而是使用了返回字节数组的 getValue()。
奇怪数字的原因是arduino存储数据的字节顺序与java不同。
使用byteBuffer改变顺序:
byte[] b = characteristic.getValue();
float f = ByteBuffer.wrap(b).order(ByteOrder.LITTLE_ENDIAN).getFloat();