使用 usb-serial 将 rts 设置为高

Using usb-serial set rts to high

我正在尝试实现这个: https://github.com/mik3y/usb-serial-for-android/blob/master/usbSerialExamples/src/main/java/src/com/hoho/android/usbserial/examples/SerialConsoleActivity.java

我有一个 LED 通过 CH340g 连接到 rts 和 5v 引脚。我已经在 android 上的 UsbTerminal 应用程序上对其进行了测试,它工作正常,但我的应用程序未检测到任何 USB 串行设备,当我尝试检查 RTS 复选框时它崩溃了。

我是编程新手,android 这是我第一次使用此类组件,因此我们将不胜感激。

这是我的代码:

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

}

如果需要更改任何内容以检测我的设备,或者是否存在任何其他问题,请告诉我。

这是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.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)

您确定已使用 static void show(Context context, UsbSerialPort port) 方法初始化 activity 并为 UsbSerialPort port 传递了 NonNull 值吗?从日志来看,似乎 mPort 变量尚未初始化。通过查看您的代码,您可以看到调用此方法时它被初始化的唯一方式。

我的猜测是您试图在不调用此方法的情况下初始化 Activity。出于本示例的目的,activity 应该仅使用 show 方法初始化(至少是第一次)。

我也查看了您尝试重新创建的示例,其中指出使用静态变量作为端口引用是实现此目的的一种 hacky 方式。举一个简单的例子,它应该没问题,但在某些情况下它可能会崩溃,如果你打算进一步使用它,最好找到一种不同的初始化方式。