【问题标题】:How to read out de incoming values send with Bluetooth?如何读出通过蓝牙发送的传入值?
【发布时间】:2019-05-17 08:56:19
【问题描述】:

我想使用从我的 Arduino 发送到我的 android 的数据。我能够将两者连接在一起并在我的屏幕上显示传入的数据。但是,当我想使用传入的数据来设置 cmets 时,这似乎不起作用。那么如何从传入的数据中获取值呢?

    String address1 = ("98:D3:81:FD:4B:87");
    String name1 = ("Sensor_Shoe");

    @SuppressLint("HandlerLeak")
    protected void bluetoothconnect() {
        btEnablingIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        requestCodeForEnable=1;
        if (myBluetoothAdapter==null){
            Toast.makeText(getApplicationContext(),"Bluetooth not supported", Toast.LENGTH_LONG).show();
        } else {
            if (!myBluetoothAdapter.isEnabled()) {
                startActivityForResult(btEnablingIntent, requestCodeForEnable);
            }
            if (myBluetoothAdapter.isEnabled()) {
                myBluetoothAdapter.disable();
                Toast.makeText(getApplicationContext(),"Bluetooth disabled",Toast.LENGTH_SHORT).show();
                TextView input1 = findViewById(R.id.input1); input1.setVisibility(View.INVISIBLE);
                ImageButton btn_bluetooth = findViewById(R.id.btn_bluetooth); btn_bluetooth.setBackgroundColor(getResources().getColor(R.color.transparent));
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if(requestCode==requestCodeForEnable){
            ImageButton btn_bluetooth = findViewById(R.id.btn_bluetooth);
            if(resultCode==RESULT_OK){
                Toast.makeText(getApplicationContext(),"Bluetooth enabled",Toast.LENGTH_SHORT).show();
                TextView input1 = findViewById(R.id.input1); input1.setVisibility(View.VISIBLE);
                btn_bluetooth.setBackgroundColor(getResources().getColor(R.color.colorAccent));
                createsocket();
            }
            else if(resultCode==RESULT_CANCELED){
                Toast.makeText(getApplicationContext(),"Bluetooth enabling cancelled",Toast.LENGTH_SHORT).show();
                TextView input1 = findViewById(R.id.input1); input1.setVisibility(View.INVISIBLE);
                btn_bluetooth.setBackgroundColor(getResources().getColor(R.color.transparent));
            }
        }
    }

    protected void createsocket() {
        new Thread() {
            public void run() {
                boolean fail = false;

                BluetoothDevice device = myBluetoothAdapter.getRemoteDevice(address1);

                try {
                    BTSocket = createBluetoothSocket(device);
                } catch (IOException e) {
                    fail = true;
                    Toast.makeText(getBaseContext(), "Socket creation failed", Toast.LENGTH_SHORT).show();
                }
                // Establish the Bluetooth socket connection.
                try {
                    BTSocket.connect();
                } catch (IOException e) {
                    try {
                        fail = true;
                        BTSocket.close();
                        BTHandler.obtainMessage(CONNECTING_STATUS, -1, -1)
                                .sendToTarget();
                    } catch (IOException e2) {
                        //insert code to deal with this
                        Toast.makeText(getBaseContext(), "Socket creation failed", Toast.LENGTH_SHORT).show();
                    }
                }
                if (!fail) {
                    mConnectedThread = new ConnectedThread(BTSocket);
                    mConnectedThread.start();
                    BTHandler.obtainMessage(CONNECTING_STATUS, 1, -1, name1)
                            .sendToTarget();
                }
            }
        }.start();
    }

    private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
        try {
            final Method m = device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", UUID.class);
            return (BluetoothSocket) m.invoke(device, PORT_UUID);
        } catch (Exception e) {
            Log.e(TAG, "Could not create Insecure RFComm Connection",e);
        }
        return  device.createRfcommSocketToServiceRecord(PORT_UUID);
    }

    private class ConnectedThread extends Thread {
        private final BluetoothSocket mmSocket;
        private final InputStream mmInStream;

        public ConnectedThread(BluetoothSocket socket) {
            mmSocket = socket;
            InputStream tmpIn = null;
            // Get the input and output streams, using temp objects because
            // member streams are final
            try {
                tmpIn = socket.getInputStream();
            } catch (IOException e) { }
            mmInStream = tmpIn;
        }

        public void run() {
            byte[] buffer = new byte[1024];  // buffer store for the stream
            int bytes; // bytes returned from read()
            // Keep listening to the InputStream until an exception occurs
            while (true) {
                try {
                    // Read from the InputStream
                    bytes = mmInStream.available();
                    if(bytes != 0) {
                        buffer = new byte[1024];
                        SystemClock.sleep(100); //pause and wait for rest of data. Adjust this depending on your sending speed.
                        bytes = mmInStream.available(); // how many bytes are ready to be read?
                        bytes = mmInStream.read(buffer, 0, bytes); // record how many bytes we actually read
                        BTHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)
                                .sendToTarget(); // Send the obtained bytes to the UI activity
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    break;
                }
            }
        }
    }

这就是我建立连接的方式,这似乎工作正常。比我使用下面的代码来读取传入的数据。

BTHandler = new Handler() {
            public void handleMessage(android.os.Message msg) {
                if (msg.what == MESSAGE_READ) {
                    String readMessage = " ";
                    try {
                        readMessage = new String((byte[]) msg.obj, "UTF-8");
                        inputdata1 = readMessage;
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    TextView input1 = findViewById(R.id.input1);
                    input1.setText(readMessage);
                    if (readMessage.equals("X")){
                        Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
                        vibrator.vibrate(100);
                    }
                }
            }
        };

在文本视图中显示传入数据有效。但它无法识别传入数据中的 X。但是,我可以看到这些数据正在 textView 中传入,并且我确实在 de arduino 代码中发送了它。

if (fsrReadingHeel >= (fsrReadingHeelOld + 800)){
    Serial.println("X");
  }

我确实知道代码已被处理,因为当我说 if (!(readMessage.equals("X"))){ 时,它会振动。

【问题讨论】:

  • 您是否尝试过使用不同/更长的消息并检查是否可以阅读?我认为 Arduino 发送 ASCII ...
  • 我试过了,但没用
  • 您是否尝试记录收到的消息并确保 UTF-8 正确,而不是 ASCII?
  • 我这样做了,我认为这就是问题所在,数据在 textview 中显示为 X,但是当我记录它时会出现很多问号。但我不明白用什么来代替 UTF-8 而 ASCII 不是字符集名称
  • 我将我的 charsetname 更改为 US-ASCII 但似乎没有任何改变,textview 仍然正确显示传入的数据,但是在记录数据时会出现许多问号。我也尝试通过从 textview 中取回字符串来解决它,但这也会导致很多问号

标签: java android bluetooth arduino serial-communication


【解决方案1】:

Arduinos Serial.print 以 ASCII 格式发送。构建字符串时,可以像这样使用 ASCII:Charset.setName("ASCII") 而不仅仅是“UTF-8”。这对我来说很好用(使用 Arduino Uno 和 HC-06 蓝牙模块):

 readMessage = new String((byte[]) msg.obj, Charset.setName("ASCII"));

您从 byteBuffer 创建的字符串应限制为实际数据的大小 - 您可以为此使用 substring(0, sizeOfData)。

当我让我的应用程序连接到我的 Arduino Uno 时,我遇到了问题,根据配置,它忽略了 Android 中第一个发送的字节,所以尝试发送一个更长的字符串,看看你是否得到了什么,然后您实际上可以正确阅读它。 我建议您使用 Serial.print 而不是 println,因为发送时不需要换行符。它还可能会更改您在 Android 上收到的消息。

if (fsrReadingHeel >= (fsrReadingHeelOld + 800)){
Serial.print("X");

}

您也可以改用 Serial.write,但您不需要 - 看看这里的区别:https://arduino.stackexchange.com/questions/10088/what-is-the-difference-between-serial-write-and-serial-print-and-when-are-they

【讨论】:

  • 我能够使它工作,我确实按照您的建议将 println 更改为打印,并将“UTF-8”更改为“US-ASCII”。我没有使用子字符串,而是在我的消息前面添加了一个随机字母,然后使用 if (ReadMessage.contains("x"))。谢谢你的建议。
  • 很高兴能帮上忙! :-)
猜你喜欢
  • 2016-05-08
  • 1970-01-01
  • 1970-01-01
  • 2020-09-19
  • 1970-01-01
  • 1970-01-01
  • 2014-11-16
  • 1970-01-01
相关资源
最近更新 更多