为什么android通过ble bt-410接收数据是字节-32

时间:2016-11-01 04:38:06

标签: android bluetooth arduino bluetooth-lowenergy

我尝试通过蓝牙低功耗bt-410在Android设备和Arduino Mega 2560之间发送和接收数据, 当我收到数据类型是byte []并且我解码为字符串它是一个问题符号所以我尝试将byte []转换为byte然后值为-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);
}

1 个答案:

答案 0 :(得分:0)

Java中的字节是签名的,而不是我见过的骨头的决定但它接近了。有可能的用例将它视为已签名是有道理的,但我想不出任何类型的头脑。我可能更喜欢使用类似byte的类型作为签名变体的未签名shorter类型: - )

在任何情况下,这意味着从通信渠道获取大于127的值将看起来像Java的负数。

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

获取您的字节,将其放入更广泛的数据类型(例如int),然后添加256

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