关于android串口通讯相关的东西,直接上代码
public class SerialPort {
private static final String TAG = "SerialPort";
private FileDescriptor mFd;
private FileInputStream mFileInputStream;
private FileOutputStream mFileOutputStream;
public SerialPort(File device, int baudrate, int flags) throws SecurityException, IOException {
if (!device.canRead() || !device.canWrite()) {
try {
Process su;
su = Runtime.getRuntime().exec("/system/bin/su");
String cmd = "chmod 666 " + device.getAbsolutePath() + "\n"
+ "exit\n";
su.getOutputStream().write(cmd.getBytes());
if ((su.waitFor() != 0) || !device.canRead()
|| !device.canWrite()) {
throw new SecurityException();
}
} catch (Exception e) {
e.printStackTrace();
throw new SecurityException();
}
}
mFd = open(device.getAbsolutePath(), baudrate, flags);
if (mFd == null) {
Log.e(TAG, "native open returns null");
throw new IOException();
}
mFileInputStream = new FileInputStream(mFd);
mFileOutputStream = new FileOutputStream(mFd);
}
public InputStream getInputStream() {
return mFileInputStream;
}
public OutputStream getOutputStream() {
return mFileOutputStream;
}
private native static FileDescriptor open(String path, int baudrate, int flags);
public native void close();
static {
System.loadLibrary("serial_port");
}
}
需要注意的是,这个文件一定要放在根目录的 android_serialport_api 的包名下
// OPEN串口通讯
try {
SerialPort serialPort = new SerialPort(new File("你的设备文件地址 eg: /dev/test"),115200,0);
} catch (IOException e){
e.printStackTrace();
}
//写入数据
mOutputStream = serialPort.getOutputStream();
if (outputStream != null) {
try {
outputStream.write(buf);
} catch (IOException e) {
}
}
// 读取数据
mInputStream = serialPort.getInputStream();
// 判断下
int readLen = mInputStream.available();
if(readLen>0){
mInputStream.read();
}
以上就是对串口的数据操作,具体的做法应该是写一个线程去处理相关操作,这里紧紧是把基本的思路做法写出来
还有一个 通用库 libserial_port.so 这个是必须的,网上有很多,下载一个就可以
补充一下:波特率 一般是115200 ,根据实际情况来写