【问题标题】:why android receive data is byte -32 via ble bt-410为什么android通过ble bt-410接收数据是字节-32
【发布时间】:2017-03-14 05:55:09
【问题描述】:

我正在尝试通过蓝牙低功耗 bt-410 在 Android 设备和 Arduino Mega 2560 之间发送和接收数据, 当我收到数据类型是字节 [] 并且我解码为字符串时,它是一个问题符号,所以我尝试将日志字节 [] 转换为字节,然后值为 -32,当我将一些字符串从我的应用程序发送到 Arduino 中的串行监视器时没什么。 如何发送和接收数据?

//Receive data:
@Override
public void onCharacteristicChanged(BluetoothGatt mGatt, BluetoothGattCharacteristic characteristic) {
        super.onCharacteristicChanged(mGatt, characteristic);

        String textRX;
        try {
             textRX = new String(characteristic.getValue(), "UTF-8");
        } catch (UnsupportedEncodingException e) {
             e.printStackTrace();
        }
        writeLine("Received: " + textRX);
        hideKeyboard();
        scrollDown();
}

//Send data:
public void sendClick(View view) {
        String message = editInput.getText().toString();
        if (tx == null || message.isEmpty()) {
            return;
        }
        try {
            value = message.getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        tx.setValue(value);
        if (mGatt.writeCharacteristic(tx)) {
            writeLine("Sent: " + message);
            editInput.setText("");
            hideKeyboard();
            scrollDown();
            Log.e("textTX", tx + "");
        } else {
            writeLine("Couldn't write TX characteristic!");
        }
}

//Arduino Code:
String inputString="";

void setup() {
  Serial.begin(9600);
}

void loop() {
  if(Serial.available() > 0) {
    inputString = Serial.readStringUntil('\n');
    Serial.println(inputString);
    if (inputString == "R1") {
      delay(100);
      Serial.println("R1 on");
    }
  }
  delay(10);
}

【问题讨论】:

    标签: android bluetooth arduino bluetooth-lowenergy


    【解决方案1】:

    Java 中的字节已签名,这不是我见过的愚蠢的决定,但它已经接近了。在某些用例中,将其视为已签名是有意义的,但我想不出任何我的想法。我可能更喜欢无符号的byte 类型,使用像shorter 这样的类型作为有符号的变体:-)

    在任何情况下,这意味着从您的通信频道获取大于 127 的值对于 Java 来说将是一个负数。

    更准确地说,它看起来像unsignedEquivalent - 256,因此应该为您提供有关如何“修复”它的线索。

    取你的字节,放入更广泛的数据类型(如int),然后添加256

    byte bdata = -32;   // should have been 224
    int idata = bdata;
    idata + 256;        // is 224
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多