Android串口通讯RS485发送和接收数据 | 您所在的位置:网站首页 › 485文件 › Android串口通讯RS485发送和接收数据 |
最近有个需求是这样子的,客户购买了我们这边的室内可视分机, 客户DIY自己的软件,我们这边需要提供RS485串口通讯demo演示以及sdk集成。 大致需求是这样子,话不多说,往下看。 一、SDK部分 1、拷贝libxxx.so文件到armeabi-v7a目录下拷贝.so库(用来进行485串口通讯的)到,libs/armeabi-v7a目录下,.so文件名称根据自己项目具体的功能模块命名名称。 串口通讯类,静态块加载.so文件,打开/关闭串口,获取输入流/输出流,定义JNI封装接口等等。 /* * Copyright 2009 Cedric Priscal * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.leecore.serialport; import android.util.Log; import java.io.File; import java.io.FileDescriptor; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; /** * @description: 串口通讯 * @version: v1.0 * @author: yeyl * @date: 2020/12/22 18:46 * @history: */ public class SerialPort { static { System.loadLibrary("xxx"); } 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 { /* Check access permission */ if (!device.canRead() || !device.canWrite()) { try { /* Missing read/write permission, trying to chmod the file */ 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) { throw new SecurityException(); } } mFd = serialPortOpen(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); } // Getters and setters public InputStream getInputStream() { return mFileInputStream; } public OutputStream getOutputStream() { return mFileOutputStream; } public void close() { try { mFileInputStream.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { mFileOutputStream.close(); } catch (IOException e) { |
CopyRight 2018-2019 实验室设备网 版权所有 |