在日常的开发过程中,我们多少会在一些开发板子上进行app开发,其中就会涉及到一些串口数据的处理,今天就记录一下,用到的串口连接和数据接收和发送
1、首先去现在下载用到的串口开发的android-serialport-api库,我这边用到的和在github上下载的可能有点出入,但是经开发过程中测试是好的
其中在SerialPort.java中需要注意的有
(1) Runtime.getRuntime().exec("/system/bin/su"); 这里面的/system/bin/su路径可能每个系统版本不一样,我开发中的路径就是/system/xbin/su
(2)确认波特率
(3)确认端口
以上两点若没有确认好的话,都会造成串口连接失败;
2、连接串口
public void initSerialPort() { try { SerialPort serial = new SerialPort(new File(""/dev/ttymxc1""), 115200, 8, 0, 1, 0); if(serial != null) { mOutputStream = serial.getOutputStream(); mInputStream = serial.getInputStream(); HandlerThread handlerThread = new HandlerThread("SerialThread"); handlerThread.start(); mHandler = new Handler(handlerThread.getLooper()); mHandler.post(threadRunnable); } } catch (Exception e) { e.printStackTrace(); } }
接收串口数据
Runnable threadRunnable = new Runnable() { @Override public void run() { try { while (true) { try { Thread.currentThread().sleep(2); } catch (InterruptedException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } if(mInputStream != null && mInputStream.available() > 0) { byte[] buffer = new byte[1024]; int n = mInputStream.read(buffer); if (n > 0) { byte[] data = new byte[n]; //处理接收到的串口数据,根据实际定的串口通信协议处理即可 //这边需要处理的一点就是,在开发过程中可能会发现某次接收到的数据并非一个完整的数据协议包,这样就需要自己拼数据包处理了 } } } } catch (IOException e) { e.printStackTrace(); } } };
向串口发送数据
public void write(byte[] buf) { if (mOutputStream != null) { try { mOutputStream.write(buf); } catch (IOException e) { e.printStackTrace(); } } }
使用完后请记得close掉串口
if( serial != null) { seral.close(); serial = null; }