0

I am trying to implement this: https://github.com/mik3y/usb-serial-for-android/blob/master/usbSerialExamples/src/main/java/src/com/hoho/android/usbserial/examples/SerialConsoleActivity.java

I have an LED connected to rts and 5v pin through CH340g. I have tested it on UsbTerminal app on android and it works fine but my app does not detect any usb serial device and it crashes when i try to check the RTS checkbox.

I am new to programming and android and its my very first experience using such components so any help would be appreciated.

Here is my code:

package com.example.dell.cashregister;

import android.content.Context;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

import com.hoho.android.usbserial.driver.UsbSerialDriver;
import com.hoho.android.usbserial.driver.UsbSerialPort;
import com.hoho.android.usbserial.driver.UsbSerialProber;
import com.hoho.android.usbserial.driver.UsbSerialPort;
import com.hoho.android.usbserial.util.HexDump;
import com.hoho.android.usbserial.util.SerialInputOutputManager;


import java.io.IOException;
import java.util.List;
import java.io.*;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ScrollView;
import android.widget.TextView;

import com.hoho.android.usbserial.driver.UsbSerialPort;
import com.hoho.android.usbserial.util.HexDump;
import com.hoho.android.usbserial.util.SerialInputOutputManager;

import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MainActivity extends Activity {

private final String TAG = MainActivity.class.getSimpleName();

private static UsbSerialPort sPort = null;

private TextView mTitleTextView;
private TextView mDumpTextView;
private ScrollView mScrollView;
private CheckBox chkDTR;
private CheckBox chkRTS;

private final ExecutorService mExecutor = Executors.newSingleThreadExecutor();

private SerialInputOutputManager mSerialIoManager;

private final SerialInputOutputManager.Listener mListener =
        new SerialInputOutputManager.Listener() {

            @Override
            public void onRunError(Exception e) {
                Log.d(TAG, "Runner stopped.");
            }

            @Override
            public void onNewData(final byte[] data) {
                MainActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        MainActivity.this.updateReceivedData(data);
                    }
                });
            }
        };

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mTitleTextView = (TextView) findViewById(R.id.demoTitle);
    mDumpTextView = (TextView) findViewById(R.id.consoleText);
    mScrollView = (ScrollView) findViewById(R.id.demoScroller);
    chkDTR = (CheckBox) findViewById(R.id.checkBoxDTR);
    chkRTS = (CheckBox) findViewById(R.id.checkBoxRTS);

    chkDTR.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            try {
                sPort.setDTR(isChecked);
            }catch (IOException x){}
        }
    });

    chkRTS.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            try {
                sPort.setRTS(isChecked);
            }catch (IOException x){}
        }
    });

}


@Override
protected void onPause() {
    super.onPause();
    stopIoManager();
    if (sPort != null) {
        try {
            sPort.close();
        } catch (IOException e) {
            // Ignore.
        }
        sPort = null;
    }
    finish();
}

void showStatus(TextView theTextView, String theLabel, boolean theValue){
    String msg = theLabel + ": " + (theValue ? "enabled" : "disabled") + "\n";
    theTextView.append(msg);
}

@Override
protected void onResume() {
    super.onResume();
    Log.d(TAG, "Resumed, port=" + sPort);
    if (sPort == null) {
        mTitleTextView.setText("No serial device.");
    } else {
        final UsbManager usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);

        UsbDeviceConnection connection = usbManager.openDevice(sPort.getDriver().getDevice());
        if (connection == null) {
            mTitleTextView.setText("Opening device failed");
            return;
        }

        try {
            sPort.open(connection);
            sPort.setParameters(115200, 8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE);

            showStatus(mDumpTextView, "CD  - Carrier Detect", sPort.getCD());
            showStatus(mDumpTextView, "CTS - Clear To Send", sPort.getCTS());
            showStatus(mDumpTextView, "DSR - Data Set Ready", sPort.getDSR());
            showStatus(mDumpTextView, "DTR - Data Terminal Ready", sPort.getDTR());
            showStatus(mDumpTextView, "DSR - Data Set Ready", sPort.getDSR());
            showStatus(mDumpTextView, "RI  - Ring Indicator", sPort.getRI());
            showStatus(mDumpTextView, "RTS - Request To Send", sPort.getRTS());

        } catch (IOException e) {
            Log.e(TAG, "Error setting up device: " + e.getMessage(), e);
            mTitleTextView.setText("Error opening device: " + e.getMessage());
            try {
                sPort.close();
            } catch (IOException e2) {
                // Ignore.
            }
            sPort = null;
            return;
        }
        mTitleTextView.setText("Serial device: " + sPort.getClass().getSimpleName());
    }
    onDeviceStateChange();
}

private void stopIoManager() {
    if (mSerialIoManager != null) {
        Log.i(TAG, "Stopping io manager ..");
        mSerialIoManager.stop();
        mSerialIoManager = null;
    }
}

private void startIoManager() {
    if (sPort != null) {
        Log.i(TAG, "Starting io manager ..");
        mSerialIoManager = new SerialInputOutputManager(sPort, mListener);
        mExecutor.submit(mSerialIoManager);
    }
}

private void onDeviceStateChange() {
    stopIoManager();
    startIoManager();
}

private void updateReceivedData(byte[] data) {
    final String message = "Read " + data.length + " bytes: \n"
            + HexDump.dumpHexString(data) + "\n\n";
    mDumpTextView.append(message);
    mScrollView.smoothScrollTo(0, mDumpTextView.getBottom());
}

/**
 * Starts the activity, using the supplied driver instance.
 *
 * @param context
 * @param driver
 */
static void show(Context context, UsbSerialPort port) {
    sPort = port;
    final Intent intent = new Intent(context, MainActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NO_HISTORY);
    context.startActivity(intent);
}

}

Please let me know if anything needs to be changed in order to detect my device or if there is any other problem.

Here is the logcat:

12-05 16:32:34.677 17322-17322/com.example.dell.cashregister 
E/AndroidRuntime: FATAL EXCEPTION: main
                                                                           Process: com.example.dell.cashregister, PID: 17322
                                                                           java.lang.NullPointerException: Attempt to invoke interface method 'void com.hoho.android.usbserial.driver.UsbSerialPort.setRTS(boolean)' on a null object reference
                                                                               at com.example.dell.cashregister.MainActivity$3.onCheckedChanged(MainActivity.java:101)
                                                                               at android.widget.CompoundButton.setChecked(CompoundButton.java:161)
                                                                               at android.widget.CompoundButton.toggle(CompoundButton.java:115)
                                                                               at android.widget.CompoundButton.performClick(CompoundButton.java:127)
                                                                               at android.view.View$PerformClick.run(View.java:20755)
                                                                               at android.os.Handler.handleCallback(Handler.java:739)
                                                                               at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                               at android.os.Looper.loop(Looper.java:145)
                                                                               at android.app.ActivityThread.main(ActivityThread.java:5835)
                                                                               at java.lang.reflect.Method.invoke(Native Method)
                                                                               at java.lang.reflect.Method.invoke(Method.java:372)
                                                                               at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
                                                                               at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)

1 Answers1

0

Are you sure you have initialised the activity using the static void show(Context context, UsbSerialPort port) method and passed a NonNull value for UsbSerialPort port? From the logs, it seems like the mPort variable has not been initialised. And from looking at your code the only way it gets initialised when you call this method.

My guess is that you are trying to initialise the Activity without calling this method. For the purpose of this example, the activity should only be initialised (at least for the first time) using the show method.

I did also take a look at the example you are trying to recreate, and it is stated there that using a static variable for the port reference is a hacky way of implementing this. For a quick example it should be ok, but it may crash in some scenarios and it would be a good idea to find a different way of initialising it if you plan to use it further.

Vlad
  • 397
  • 1
  • 12