我需要一些帮助! 我需要通过COM端口从设备发送一些NMEA数据到Android平板电脑上的USB端口。当我将我的silab CP210x UART Bridge连接到平板电脑时,它会自动启动我的程序,但是当我尝试发送一些数据时,我的程序看不到它。我正在使用usb-serial-for-android库(https://github.com/mik3y/usb-serial-for-android)。我按照github的所有说明进行操作。 这是我的代码:
package com.example.simplexyplotactivity;
import java.io.IOException;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.PointF;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbManager;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.util.EventLog;
import android.util.FloatMath;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
import com.androidplot.Plot;
import com.androidplot.ui.SizeLayoutType;
import com.androidplot.ui.SizeMetrics;
import com.androidplot.xy.BoundaryMode;
import com.androidplot.xy.LineAndPointFormatter;
import com.androidplot.xy.PointLabelFormatter;
import com.androidplot.xy.SimpleXYSeries;
import com.androidplot.xy.XYPlot;
import com.hoho.android.usbserial.driver.UsbSerialDriver;
import com.hoho.android.usbserial.driver.UsbSerialProber;
import com.hoho.android.usbserial.driver.UsbSerialPort;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.hardware.usb.UsbDevice;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;
public class Simple_xy_plot_example extends Activity implements OnTouchListener {
private int com_cnt;
private String buf;
private String[] fields;
private int buf_max_length;
private int buf_idx;
private boolean buf_started;
public float course=0;
SoundPool sound_pool;
int rot_sound_ID;
private static final String ACTION_USB_PERMISSION ="com.prolific.pl2303hxdsimpletest.USB_PERMISSION";
private static final int SERIES_SIZE = 200;
private XYPlot plotOne;
private SimpleXYSeries series1 = null;
private PointF minXY;
private PointF maxXY;
NMEA_Receiver data;
private Thread myThread;
private String str;
private String stroka;
float zoomRatio = 2, leftBoundary, rightBoundary;
USB2ComDetector mUSB2ComDetector;
Handler CBhandler;
private UsbManager usb_manager;
private static UsbSerialPort ser_port = null;
ComponentName service_name;
byte temp_buf[]=new byte[4096];
private class MyPlotUpdater implements Observer {
Plot plot;
public MyPlotUpdater(Plot plot) {
this.plot = plot;
}
@Override
public void update(Observable o, Object arg) {
plot.redraw();
}
}
private boolean USB2ComConnect() {
/*if (ser_port != null) return false;
List<UsbSerialDriver> availableDrivers = UsbSerialProber.getDefaultProber().findAllDrivers(usb_manager);
if (availableDrivers.isEmpty()) {
} else {
// open connection to first avail. driver
UsbSerialDriver driver = availableDrivers.get(0);
UsbDeviceConnection connection = usb_manager.openDevice(driver.getDevice());
if (connection == null) {
} else { // Read some data! Most have just one port (port 0).
List<UsbSerialPort> myPortList = driver.getPorts();
UsbSerialPort port = myPortList.get(0);
try {
port.open(connection);
port.setParameters(4800, 8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE); // sets baud rate,databits, stopbits, & parity
byte temp_buf[]=new byte[4096]; // 1 byte per pressure sensor, plus 2 bytes for carriage return
int numBytesRead = port.read(temp_buf, 1000);
String arduinoData = new String(temp_buf, "US-ASCII");
Toast.makeText(getApplicationContext(), arduinoData, Toast.LENGTH_SHORT).show(); // Toast debugging
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "Error: couldn't read data from USB device", Toast.LENGTH_LONG).show(); // Toast debugging
}
}
}
/* List<UsbSerialPort> ports=availableDrivers.get(0).getPorts();
ser_port=ports.get(0);
UsbDeviceConnection connection=usb_manager.openDevice(ser_port.getDriver().getDevice());
try {
ser_port.open(connection);
ser_port.setParameters(4800, UsbSerialPort.DATABITS_8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE);
ser_port.purgeHwBuffers(true, true);
} catch (IOException e) {
Log.e("NMEAParser", "Cant open or set parameter to serial port");
e.printStackTrace();
return true;
}*/
return false;
}
//**********
public boolean IsCOMopened(){return ser_port!=null?true:false;}
private MyPlotUpdater plotUpdater;
public void onResume() {
// kick off the data generating thread:
myThread = new Thread(data);
myThread.start();
super.onResume();
// try {
// data.EnableRec(true);
// } catch (IOException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
// }
}
public void stopThread() {
keepRunning = false;
}
@Override
public void onPause() {
// data.stopThread();
super.onPause();
}
private boolean keepRunning = false;
class NMEA_Receiver implements Runnable {
private static final int SAMPLE_SIZE = 30;
public int k = 1;
private int kk = 1;
private UsbSerialDriver driver;
private boolean rec_enabled=false;//enable/disable when cable plug in/off
private boolean rec_alive=true;//to terminate thread when stop app
byte rec_buf[]=new byte[256];
boolean rec_started=false;
boolean trans_started;
private boolean buf_started;
private String buf;
int rec_idx=0;
NMEA_Receiver(UsbSerialDriver driver){
this.driver=driver;
}
public void stopThread() {
keepRunning = false;
}
synchronized private void SuspendRec(){
}
synchronized public void EnableRec(boolean en) throws IOException {
rec_enabled = en;
UsbDevice dev;
if (en) {
try {
//driver.open();
//driver.setBaudRate(4800);
}
catch (NullPointerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else {
//driver.close();
}
}
// ***********************************************************************************
// ***********************************************************************************
String GetRecBuf(){
return new String(rec_buf);
}
// ***********************************************************************************
public int Transmit(String tr_buf){
return 1;
}
// ***********************************************************************************
public boolean IsCOMMConnected(){
// return mPL2303.isConnected();
return false;
}
public void run() {
//byte temp_buf[]=new byte[4096];
int yy1;
int yy2;
int yy3;
int yy4;
int yy5;
int i=0;
int length=0;
try {
length=ser_port.read(temp_buf, 1000);
} catch (Exception e) {
e.printStackTrace();
}
String str2;
String str3, str4, str5;
boolean terminate=false;
keepRunning = true;
while (keepRunning) {
str5=temp_buf.toString();
Toast toast = Toast.makeText(getApplicationContext(),
str5, Toast.LENGTH_SHORT);
toast.show();
for(int k=0;k<length;k++){
if (temp_buf[0]=='$') {
buf_started = true;
}
if(buf_started){
buf+=(char)temp_buf[k];
if(temp_buf[k]=='\n'){
str = buf;
yy1 = Character.getNumericValue(str.charAt(7));
if (str.charAt(8) == '.') {
str3 = String.valueOf(str.charAt(8));
str2 = "" + yy1 + str3;
} else {
yy2 = Character.getNumericValue(str.charAt(8));
str2 = "" + yy1 + yy2;
}
if (str.charAt(9) == '.') {
str4 = String.valueOf(str.charAt(9));
str2 = str2 + str4;
} else {
if ((str.charAt(9) >= '0' && str.charAt(9) <= '9')) {
yy3 = Character.getNumericValue(str.charAt(9));
str2 = str2 + yy3;
}
}
if (str.charAt(10) == '.') {
str4 = String.valueOf(str.charAt(10));
str2 = str2 + str4;
} else if ((str.charAt(10) >= '0' && str.charAt(10) <= '9')) {
yy4 = Character.getNumericValue(str.charAt(10));
str2 = str2 + yy4;
}
if ((str.charAt(11) >= '0' && str.charAt(11) <= '9')) {
yy5 = Character.getNumericValue(str.charAt(11));
str2 = str2 + yy5;
}
course = Float.parseFloat(str2); //добавить необходимое число
kk++;
series1.addLast(kk, course);
plotOne.setRangeLabel(String.valueOf(course));
plotOne.redraw();// для выведения глубины
}
}
}
}
}
public Number getY(int series, int max) {
return 1;
}
}
public class USB2ComDetector extends BroadcastReceiver{
@Override
public void onReceive(Context arg0, Intent arg1) {
//try {
//data.EnableRec(false);
//} catch (IOException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
// }
}
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_simple_xy_plot_example);
// USB2ComConnect();
// try{
// USB2ComConnect();}
// catch (NullPointerException e){
// e.printStackTrace();
// }
// UsbManager usb_mngr=(UsbManager)getSystemService(Context.USB_SERVICE);
// List<UsbSerialDriver> availableDrivers = UsbSerialProber.getDefaultProber().findAllDrivers(usb_mngr);
//if(availableDrivers.isEmpty()==false){
// List<UsbSerialPort> ports=availableDrivers.get(0).getPorts();
// UsbDeviceConnection connection=usb_mngr.openDevice(ports.get(0).getDriver().getDevice());
// }
//
//UsbSerialDriver driver = UsbSerialProber.getDefaultProber().findAllDrivers(usb_manager);
//data = new NMEA_Receiver();
try {
if (UsbManager.ACTION_USB_DEVICE_ATTACHED.isEmpty()){
Toast toast = Toast.makeText(getApplicationContext(),
"FAIL", Toast.LENGTH_SHORT);
toast.show();
}
//try {
// data.EnableRec(true);
//} catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();}
} catch (NullPointerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);
List<UsbSerialDriver> availableDrivers = UsbSerialProber.getDefaultProber().findAllDrivers(manager);
if (availableDrivers.isEmpty()) {
return;
}
UsbSerialDriver driver = availableDrivers.get(0);
UsbDeviceConnection connection = manager.openDevice(driver.getDevice());
if (connection == null) {
return;
}
// Read some data! Most have just one port (port 0).
List<UsbSerialPort> myPortList = driver.getPorts();
UsbSerialPort port = myPortList.get(0);
try {
port.open(connection);
port.setParameters(4800, 8, UsbSerialPort.STOPBITS_1,UsbSerialPort.PARITY_NONE); // sets baud rate,databits, stopbits, & parity
} catch (IOException e) {
Toast.makeText(getApplicationContext(),"Error: couldn't read data from USB device",Toast.LENGTH_LONG).show(); // Toast debugging
}
mUSB2ComDetector=new USB2ComDetector();
IntentFilter filter=new IntentFilter();
filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
registerReceiver(mUSB2ComDetector,filter);
sound_pool=new SoundPool(1, AudioManager.STREAM_MUSIC,0);
rot_sound_ID=sound_pool.load("/system/media/audio/ui/VideoRecord.ogg",1 );
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
//plot setup
plotOne = (XYPlot) findViewById(R.id.myFirstXYPlot);
plotOne.setOnTouchListener(this);
plotOne.getGraphWidget().setTicksPerRangeLabel(2);
plotOne.getGraphWidget().setTicksPerDomainLabel(2);
plotOne.getGraphWidget().setRangeLabelWidth(25);
//plotOne.setRangeLabel("");
plotOne.setDomainLabel("");
plotOne.setBorderStyle(Plot.BorderStyle.NONE, null, null);
plotOne.getLayoutManager().remove(plotOne.getLegendWidget());
plotOne.getGraphWidget().setSize(new SizeMetrics(0,SizeLayoutType.FILL,
0, SizeLayoutType.FILL));
plotOne.setPlotMargins(0,0,0,0);
//********
//series setup
series1 = new SimpleXYSeries("PARAM");
series1.useImplicitXVals();
LineAndPointFormatter line1 = new LineAndPointFormatter();
line1.setPointLabelFormatter(new PointLabelFormatter());
plotOne.addSeries(series1, line1);
plotOne.redraw();
plotOne.calculateMinMaxVals();
minXY = new PointF(plotOne.getCalculatedMinX().floatValue(),
plotOne.getCalculatedMinY().floatValue());
maxXY = new PointF(plotOne.getCalculatedMaxX().floatValue(),
plotOne.getCalculatedMaxY().floatValue());
leftBoundary = series1.getX(0).floatValue();
rightBoundary = series1.getX(series1.size() - 1).floatValue();
}
//*****************
// Definition of the touch states
static final int NONE = 0;
static final int ONE_FINGER_DRAG = 1;
static final int TWO_FINGERS_DRAG = 2;
int mode = NONE;
PointF firstFinger;
float distBetweenFingers;
boolean stopThread = false;
@Override
public boolean onTouch(View arg0, MotionEvent event) {
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN: // Start gesture
firstFinger = new PointF(event.getX(), event.getY());
mode = ONE_FINGER_DRAG;
stopThread = true;
break;
case MotionEvent.ACTION_POINTER_UP:
case MotionEvent.ACTION_UP:
mode = NONE;
break;
case MotionEvent.ACTION_POINTER_DOWN: // second finger
distBetweenFingers = spacing(event);
// the distance check is done to avoid false alarms
if (distBetweenFingers > 5f) {
mode = TWO_FINGERS_DRAG;
}
break;
case MotionEvent.ACTION_MOVE:
if (mode == ONE_FINGER_DRAG) {
PointF oldFirstFinger = firstFinger;
firstFinger = new PointF(event.getX(), event.getY());
scroll(oldFirstFinger.x - firstFinger.x);
plotOne.setDomainBoundaries(minXY.x, maxXY.x,
BoundaryMode.FIXED);
plotOne.redraw();
} else if (mode == TWO_FINGERS_DRAG) {
float oldDist = distBetweenFingers;
distBetweenFingers = spacing(event);
zoom(oldDist / distBetweenFingers);
plotOne.setDomainBoundaries(minXY.x, maxXY.x,
BoundaryMode.FIXED);
plotOne.redraw();
}
break;
}
return true;
}
private void zoom(float scale) {
float domainSpan = maxXY.x - minXY.x;
float oldMax = maxXY.x;
float oldMin = minXY.x;
float domainMidPoint = maxXY.x - (domainSpan / 2.0f);
float offset = domainSpan * scale / 2.0f;
minXY.x = domainMidPoint - offset;
maxXY.x = domainMidPoint + offset;
float newSpan = maxXY.x - minXY.x;
if (newSpan < (float)5) {
minXY.x = oldMin;
maxXY.x = oldMax;
}
if (minXY.x < leftBoundary) {
minXY.x = leftBoundary;
maxXY.x = leftBoundary + domainSpan * zoomRatio;
if (maxXY.x > series1.getX(series1.size() - 1).floatValue())
maxXY.x = rightBoundary;
}
if (maxXY.x > series1.getX(series1.size() - 1).floatValue()) {
maxXY.x = rightBoundary;
minXY.x = rightBoundary - domainSpan * zoomRatio;
if (minXY.x < leftBoundary) minXY.x = leftBoundary;
}
}
private void scroll(float pan) {
float domainSpan = maxXY.x - minXY.x;
float step = domainSpan / plotOne.getWidth();
float offset = pan * step;
minXY.x = minXY.x + offset;
maxXY.x = maxXY.x + offset;
if (minXY.x < leftBoundary) {
minXY.x = leftBoundary;
maxXY.x = leftBoundary + domainSpan;
}
if (maxXY.x > series1.getX(series1.size() - 1).floatValue()) {
maxXY.x = rightBoundary;
minXY.x = rightBoundary - domainSpan;
}
}
private float spacing(MotionEvent
event) {
float x = event.getX(0) - event.getX(1);
float y = event.getY(0) - event.getY(1);
return FloatMath.sqrt(x * x + y * y);
}
}
答案 0 :(得分:0)
使用库usb-serial-for-android
时,我遇到了类似的问题。我将字节写入串口,但我的Arduino无法获得任何信号。过了一会儿,我发现AndroidApp DroidTerm
可以直截了当地做我想做的事。它使用https://github.com/felHR85/UsbSerial
作为DroidTerm的串行端口驱动程序库。我发现这个库支持Silicon Lab CP21xx UART等等:
..支持的设备目前UsbSerial支持三种最常用的设备 USB转串口芯片组: - FTDI FT232(我不打算把你的设备搞定,相信我:)) - Silicon Labs CP210x - 多产PL2303HX(至少HX版) - CH340 / CH341 ..
所以它可以解决你的问题。