1

I went through lots of demos and SO threads before asking this, but none of them is working for me. I am trying to read data over usb serial port using the below code.

public class MainActivity extends Activity {
    public final String ACTION_USB_PERMISSION = "com.myprject.usbex.USB_PERMISSION";
    Button startButton, sendButton, clearButton, stopButton;
    TextView textView;
    EditText editText;
    UsbManager usbManager;
    UsbDevice device;
    UsbSerialDevice serialPort;
    UsbDeviceConnection connection;

    UsbSerialInterface.UsbReadCallback mCallback = new UsbSerialInterface.UsbReadCallback() { //Defining a Callback which triggers whenever data is read.
        @Override
        public void onReceivedData(byte[] arg0) {
            Toast.makeText(MainActivity.this, "Callback Received"+arg0, Toast.LENGTH_SHORT).show();
            String data = null;
            try {
                data = new String(arg0, "UTF-8");
                data.concat("/n");
                tvAppend(textView, data);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                Toast.makeText(MainActivity.this, "Exception:"+e.getMessage(), Toast.LENGTH_SHORT).show();
            }


        }
    };
    private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() { //Broadcast Receiver to automatically start and stop the Serial connection.
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(ACTION_USB_PERMISSION)) {
                boolean granted = intent.getExtras().getBoolean(UsbManager.EXTRA_PERMISSION_GRANTED);
                if (granted) {
                    connection = usbManager.openDevice(device);
                    serialPort = UsbSerialDevice.createUsbSerialDevice(device, connection);
                    if (serialPort != null) {
                        if (serialPort.open()) { //Set Serial Connection Parameters.
                            setUiEnabled(true);
                            serialPort.setBaudRate(9600);
                            serialPort.setDataBits(UsbSerialInterface.DATA_BITS_8);
                            serialPort.setStopBits(UsbSerialInterface.STOP_BITS_1);
                            serialPort.setParity(UsbSerialInterface.PARITY_NONE);
                            serialPort.setFlowControl(UsbSerialInterface.FLOW_CONTROL_OFF);
                            try {
                                serialPort.read(mCallback);
                                Toast.makeText(MainActivity.this, "Read"+serialPort.read(mCallback), Toast.LENGTH_SHORT).show();
                            } catch (Exception e) {
                                Toast.makeText(MainActivity.this, "Exception in read:"+e.getMessage(), Toast.LENGTH_SHORT).show();
                            }
                            tvAppend(textView, "Serial Connection Opened!\n");
                            Toast.makeText(MainActivity.this, "Serial port connected", Toast.LENGTH_SHORT).show();
                        } else {
                            Log.d("SERIAL", "PORT NOT OPEN");
                        }
                    } else {
                        Log.d("SERIAL", "PORT IS NULL");
                    }
                } else {
                    Log.d("SERIAL", "PERM NOT GRANTED");
                }
            } else if (intent.getAction().equals(UsbManager.ACTION_USB_DEVICE_ATTACHED)) {
                onClickStart(startButton);
            } else if (intent.getAction().equals(UsbManager.ACTION_USB_DEVICE_DETACHED)) {
                onClickStop(stopButton);

            }
        }

        ;
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        usbManager = (UsbManager) getSystemService(this.USB_SERVICE);
        startButton = (Button) findViewById(R.id.buttonStart);
        sendButton = (Button) findViewById(R.id.buttonSend);
        clearButton = (Button) findViewById(R.id.buttonClear);
        stopButton = (Button) findViewById(R.id.buttonStop);
        editText = (EditText) findViewById(R.id.editText);
        textView = (TextView) findViewById(R.id.textView);
        setUiEnabled(false);
        IntentFilter filter = new IntentFilter();
        filter.addAction(ACTION_USB_PERMISSION);
        filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
        filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
        registerReceiver(broadcastReceiver, filter);


    }

    public void setUiEnabled(boolean bool) {
        startButton.setEnabled(!bool);
        sendButton.setEnabled(bool);
        stopButton.setEnabled(bool);
        textView.setEnabled(bool);

    }

    public void onClickStart(View view) {

        HashMap<String, UsbDevice> usbDevices = usbManager.getDeviceList();
        if (!usbDevices.isEmpty()) {
            boolean keep = true;
            for (Map.Entry<String, UsbDevice> entry : usbDevices.entrySet()) {
                device = entry.getValue();
                int deviceVID = device.getVendorId();
                if (deviceVID == 1659)//Arduino Vendor ID
                {
                    PendingIntent pi = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
                    usbManager.requestPermission(device, pi);
                    keep = false;
                } else {
                    connection = null;
                    device = null;
                }

                if (!keep)
                    break;
            }
        }


    }

    public void onClickSend(View view) {
        String string = editText.getText().toString();
        serialPort.write(string.getBytes());
        tvAppend(textView, "\nData Sent : " + string + "\n");

    }

    public void onClickStop(View view) {
        setUiEnabled(false);
        serialPort.close();
        tvAppend(textView,"\nSerial Connection Closed! \n");

    }

    public void onClickClear(View view) {
        textView.setText(" ");
    }

    private void tvAppend(TextView tv, CharSequence text) {
        final TextView ftv = tv;
        final CharSequence ftext = text;

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                ftv.append(ftext);
            }
        });
    }

}

I want to read data continuously from the usb. With above code I am able to get device vendor-id and serialPort.open() is also working. Problem is that I am not receiving the data.

Library used with this code is from here https://github.com/felHR85/SerialPortExample.

Point me where I am going wrong. open for any alternative solution to read data over usb in Android.

karan
  • 8,637
  • 3
  • 41
  • 78

3 Answers3

0

The code seems to be right and is working properly. Tried it and it runs smoothly without any problems. You might want to rearrange your widgets a little bit, which could be obstructing/interfering with your output (although I don't think this could be the problem). The toast in onReceivedData function was causing the app to crash. Also, check your Arduino device vendor ID. Mine was different (0x2341 for Arduino UNO R3).

archity
  • 562
  • 3
  • 11
  • 22
  • Welcome to StackOvervlow @archity, and thank you for joining the discussion! Your experience is helpful, but it should be a comment on the original question instead of an answer. – eebbesen Jul 02 '16 at 12:20
  • A polite response on bad usage... you don't belong in Stackoverflow xd – Raul Lapeira Herrero Dec 30 '18 at 10:53
0

Hello I know its too late for a reply but here it goes.

                      serialPort.setBaudRate(9600);
                      serialPort.setDataBits(UsbSerialInterface.DATA_BITS_8);
                      serialPort.setStopBits(UsbSerialInterface.STOP_BITS_1);
                      serialPort.setParity(UsbSerialInterface.PARITY_NONE);
                      serialPort.setFlowControl(UsbSerialInterface.FLOW_CONTROL_OFF);

Make sure that these are the config set at your USB Device, try changing BaudRate

Syed Afeef
  • 140
  • 1
  • 9
0

i guess that library is specially designed for Arduino and some boards. I tried with PSOc Usb serial data transfer from its ROM, The data was not able to be read properly.