Search code examples
javaandroidbluetootharduinoserial-communication

How to read out de incoming values send with Bluetooth?


I want to use data sent from my Arduino to my android. I'm able to connect both together and display the incoming data on my screen. However, when I want to use the incoming data to set comments this doesn't seem to be working. So how can I get the values out of the incoming data?

    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;
                }
            }
        }
    }

This is how I make the connection, this seems to work properly. Than I use the code underneith to read out the incomming data.

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);
                    }
                }
            }
        };

Showing the incomming data in the textview works. But it doesn't recognize the X in the incomming data. I can however see that this data is incomming in the textView and i do send this in de arduino code.

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

I do know the code is processed because when I say if (!(readMessage.equals("X"))){ than it does vibrate.


Solution

  • Arduinos Serial.print sends in ASCII. When you build a String, you can use ASCII like this: Charset.setName("ASCII") instead of just "UTF-8". This works fine for me (with a Arduino Uno and HC-06 Bluetooth module):

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

    The String you created from the byteBuffer should be limited to the size of the actual data - you could use substring(0, sizeOfData) for that.

    When I made my App to connect with my Arduino Uno, I had the problem, that depending on the configuration it ignored the first sent Byte in Android, so try to send a longer string and see if you get something, and that you can actually read it correctly. I am suggesting that you use Serial.print instead of println, because you don't need the line break in sending. It might also change the message you receive on Android.

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

    }

    You could also use Serial.write instead, but you don't need to - have a look at the differences here: https://arduino.stackexchange.com/questions/10088/what-is-the-difference-between-serial-write-and-serial-print-and-when-are-they