android 串口通讯

本文介绍了Android设备上的串口通信实现,强调了代码放置的位置和串口操作的基本思路。提到了需要一个通用库libserial_port.so,并指出常见的波特率是115200,但实际使用中应按需设定。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

关于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  ,根据实际情况来写

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值