将ASCII表char转换为ASCII表小数

时间:2018-03-28 22:04:57

标签: android c++ arduino bluetooth-lowenergy ascii

我正在使用Arduino和Android。尝试使用BLE将数据从Android手机发送到ESP32设备。我在从Android端接收数据时遇到问题。

例如,我会在Android上用以下Java代码写入ESP32:

mBluetoothLeService.writeCustomCharacteristic(0xFFFF);

其中writeCustomCharacteristic()函数如下:

 public void writeCustomCharacteristic(int value) {
    if (mBluetoothAdapter == null || mBluetoothGatt == null) {
        Log.w(TAG, "BluetoothAdapter not initialized");
        return;
    }
    /*check if the service is available on the device*/
    BluetoothGattService mCustomService = mBluetoothGatt.getService(UUID.fromString("00001110-0000-1000-8000-00805f9b34fb"));
    if(mCustomService == null){
        Log.w(TAG, "Custom BLE Service not found");
        return;
    }
    /*get the read characteristic from the service*/
    BluetoothGattCharacteristic mWriteCharacteristic = mCustomService.getCharacteristic(UUID.fromString("00000001-0000-1000-8000-00805f9b34fb"));
    mWriteCharacteristic.setValue(value,android.bluetooth.BluetoothGattCharacteristic.FORMAT_UINT8,0);
    if(mBluetoothGatt.writeCharacteristic(mWriteCharacteristic) == false){
        Log.w(TAG, "Failed to write characteristic");
    }
}

现在,在Arduino方面,我想收到正确的0xFFFF,但它给了我垃圾字符。

以下行是ESP32接收数据的地方,数据包含在rxValue:

 class MyCallbacks: public BLECharacteristicCallbacks {
void onWrite(BLECharacteristic *pCharacteristic) {
  std::string rxValue = pCharacteristic->getValue();

  if (rxValue.length() > 0) {
    Serial.println("*********");
    Serial.print("Received Value: ");
    for (int i = 0; i < rxValue.length(); i++)
      Serial.print(rxValue[i]);

    Serial.println();
    Serial.println("*********");
  }
}
};

我的问题是,如何将该垃圾字符转换回0xFFFF?
我试着做int(rxValue[i])byte(rxValue[i]),但这只给了我255,现在我怎么得到第二个字节?

此外,rxValue [0]具有数据,其他索引为空。

writeCustomCharacteristic()函数与教程相同,没有做任何更改。 这是arduino代码的link,它来自esp32库示例。

解决方案 根据Barns的建议,我只是将数据格式更改为如下所示的FORMAT_UINT16更大的内容。

mWriteCharacteristic.setValue(value,android.bluetooth.BluetoothGattCharacteristic.FORMAT_UINT16,0);

由此,我能够从android端获得实际数据。

1 个答案:

答案 0 :(得分:1)

您遇到此问题,因为您用于发送数据的代码(显然是从在线教程中获取的代码)与您发送的数据大小不符。

您只收到255,因为您用来发送数据的代码使用的是特征值格式类型sint8 FORMAT_UINT8(255显然反映了这种格式),但是您发送的数据( 0xFFFF)至少是uint16,因此你应该使用FORMAT_UINT16(uint16的特征值格式类型)。

请熟悉Android文档:

https://developer.android.com/reference/android/bluetooth/BluetoothGatt.html#writeCharacteristic(android.bluetooth.BluetoothGattCharacteristic)

以及此链接,以便更好地了解如何设置您要发送的特征

https://developer.android.com/reference/android/bluetooth/BluetoothGattCharacteristic.html

为了更好地理解可能性和限制。

<强> - 声明 -

在您发布实际代码之前,您使用此答案只是尝试解释您遇到的问题。