读取 BLE 特性时出现问题

问题描述 投票:0回答:1

我使用 arduino nano 上的软件序列每秒从 HC08 模块发送一个大小为 8 的字节数组。但是,当我尝试从 Android 应用程序读取特征时(我也每秒读取一次),onChracteristicread 每次都会被调用,但是接收到的数据始终为 0。我正在从 SERVICE_UUID 读取: UUID = UUID.fromString("0000ffe0-0000-1000-8000-00805f9b34fb") CHARACTERISTIC_UUID: UUID = UUID.fromString("0000ffe1-0000-1000-8000-00805f9b34fb") ,我认为这是FFE0和FFE1的完整形式。我错过了什么步骤吗?

override fun onCharacteristicRead(
            gatt: BluetoothGatt,
            characteristic: BluetoothGattCharacteristic,
            status: Int
        ) {
            super.onCharacteristicRead(gatt, characteristic, status)

            if (status == BluetoothGatt.GATT_SUCCESS) {
                // Read the value from the characteristic
                // Update the readValue variable
                readValue = characteristic.value
                val s = characteristic.value.size
                // Log the read status
                Log.v("bluetooth", "onCharacteristicRead size: $s")
            } else {
                // Log if the read operation failed
                Log.e("bluetooth", "onCharacteristicRead: failed")
            }
        }

下面是Arduino的代码。

#include <SoftwareSerial.h>

SoftwareSerial HC08(2,3);

void setup() {
  Serial.begin(9600);
  HC08.begin(9600);
}
  float value1 = 0;
  float value2 = 10;
void loop() {  
  byte bytes[8]; // Array to hold bytes for two floats
  
  byte *bytePtr = (byte *)&value1;
  for (int i = 0; i < 4; i++) {
      bytes[i] = bytePtr[i];
  }
  
  bytePtr = (byte *)&value2;
  for (int i = 0; i < 4; i++) {
      bytes[i + 4] = bytePtr[i];
  }
  
  // Now, send the bytes array over Bluetooth
  Serial.print("Sent data\n");
 HC08.write(bytes, sizeof(bytes));
//HC08.write("abc");
  value1++;
  value2--;
  delay(1000);
}

我很确定它确实发送了数据,因为接收到的数据可以在服务ID FFE0和特征ID FFE1下找到(我使用“nRF connect”来确认这一点)

android kotlin bluetooth-lowenergy
1个回答
0
投票

@蔡茗钧 你说得对。

对于仍然遇到此问题的人,我正在写这个答案。

读取BLE特性时,我们有这个方法:

onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status)

此方法仍然适用于低于 33 的 API 级别,但在 API 级别 33 中已弃用,因此我们必须使用:

onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, byte[] value, int status)
© www.soinside.com 2019 - 2024. All rights reserved.