前段时间用android端开发物联网,其中用到了485通讯,关于485通讯知识的介绍:http://blog.chinaunix.net/uid-26921272-id-3506640.html
232通讯是两根数据线一个收一个发,但是485通讯是两线合作收发,芯片有一个状态控制端,也就是控制端口的高低电平来决定是收状态还是发状态,android上是用proc节点的方式控制处理器外部端口的状态的,下面就是如何读取proc节点:
核心代码示例:
File myFile = new File("proc/tp_debug/debug_switch"); FileWriter fr; try { fr = new FileWriter( myFile ); fr.write("1"); //1是发送出数据,0是接收进数据 fr.close(); } catch (IOException e) { e.printStackTrace(); }
package com.hehe.haha; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import android.os.Bundle; import android.util.Log; import com.hehe.haha.base.BaseActivity; import com.hehe.haha.base.BaseApp; import com.hehe.haha.base.SerialPort; /** send and receive of serial port */ public abstract class SerialPortActivity extends BaseActivity { private static final String TAG = "SerialPortActivity"; protected BaseApp mApplication; protected SerialPort mSerialPort; protected OutputStream mOutputStream; private InputStream mInputStream; private ReadThread mReadThread; private class ReadThread extends Thread { @Override public void run() { super.run(); int maxLength = 10; byte[] buffer = new byte[maxLength];//缓存区 while (!isInterrupted()) { try { int size; if (mInputStream == null) { return; } size = mInputStream.read(buffer); //防止溢出 if (size == 10) { onDataReceived(buffer, 10); } } catch (IOException e) { e.printStackTrace(); return; } } } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); try { mApplication = (BaseApp) getApplication(); mSerialPort = mApplication.getSerialPort(); mOutputStream = mSerialPort.getOutputStream(); mInputStream = mSerialPort.getInputStream(); /* Create a receiving thread */ mReadThread = new ReadThread(); mReadThread.start(); } catch (Exception e) { DisplayError(R.string.error_configuration); } } /** * send order * * @param str */ protected void sendOrder(String str) { try { Log.i("send data", str); setSerialStu(1); for (int i = 0; i < str.length(); i = i + 2) {//Integer.parseInt(str.substring(i, i + 2), 16) mOutputStream.write(Integer.parseInt(str.substring(i, i + 2), 16));//new String(text).getBytes() } setSerialStu(0); } catch (Exception e) { e.printStackTrace(); } } /** *这里是今天笔记的重点 * set status of 485 * @param stu * 1 is send,0 is receive */ protected void setSerialStu(int stu) { File SerialCtrl = new File("proc/rp_button/485_ctrl"); FileWriter fr; try { fr = new FileWriter(SerialCtrl); //485:0-- rx 1-- tx switch (stu) { case 0: fr.write("0"); Log.i("ConsoleActivity", "this is receive"); break; case 1: fr.write("1"); Log.i("ConsoleActivity", "this is send"); break; } fr.close(); } catch (IOException e) { e.printStackTrace(); } } //接收数据时调用 protected abstract void onDataReceived(final byte[] buffer, final int size); @Override protected void onDestroy() { if (mReadThread != null) mReadThread.interrupt(); mApplication.closeSerialPort(); mSerialPort = null; super.onDestroy(); } }