美文网首页
安卓串口通讯发送指令代码详解

安卓串口通讯发送指令代码详解

作者: 心中有梦丶身边有你 | 来源:发表于2018-06-25 10:54 被阅读0次

    最近好多做安卓端跟硬件交互的,比如一些智能家居,贩卖机的。
    而这些不管是485也好,232的板子也好,都会用到串口通讯,去往下位机发送指令操控。下面是我个人的一些理解,发送串口指令的方法都是一样的,各位用的时候直接拷贝过去,改一下波特率和串口号就可以测试了。
    总代码:一个activity,两个工具类,一个声明全局变量的类,布局有一个edit发送指令,一个发送按钮,一个接收数据显示的textview
    至于jni的一些文件夹和一些so文件就要自己去弄了,
    activity的xml布局:

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
    
        <EditText
            android:id="@+id/et_main_input"
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:background="@drawable/cycle_corner_border"
            android:textSize="18sp"
            android:layout_marginTop="10dp"
            android:layout_marginLeft="20dp"
            android:layout_marginRight="20dp"
            android:paddingLeft="8dp"
            android:hint="输入的指令"/>
        <Button
            android:id="@+id/btn_main_send"
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:text="发送"/>
        <TextView
            android:id="@+id/tv_main_show"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textSize="18sp"
            android:layout_marginTop="10dp"
            android:layout_marginLeft="20dp"
            android:layout_marginRight="20dp"
            android:hint="这里显示接收到的串口数据"/>
    </LinearLayout>
    
    

    MainActivity:

    public class MainActivity extends Activity {
    
        private EditText editInput;
        private Button btnSend;
        private static TextView textShow;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            init();
        }
    
        /**
         * 初始化UI控件
         */
        private void init() {
            editInput = findViewById(R.id.et_main_input);
            btnSend = findViewById(R.id.btn_main_send);
            textShow = findViewById(R.id.tv_main_show);
            //打开串口
            SerialPortUtil.openSrialPort();
            btnSend.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onSend();//点击发送调用onSend
                }
            });
        }
    
        /**
         * 发送串口数据
         */
        private void onSend() {
            String input = editInput.getText().toString();
            if(TextUtils.isEmpty(input)){
               editInput.setError("要发送的数据不能为空");
                return;
            }
          //发送指令
            SerialPortUtil.sendSerialPort(input);
        }
    
        /**
         * 刷新UI界面
         * @param data 接收到的串口数据
         */
        public static void refreshTextView(String data){
            Log.i(TAG, "refreshTextView: "+strTo16(data));//打印接收到的数据
       textShow.setText(textShow.getText().toString()+";"+strTo16(data));
        }
    
        /**
         * 字符串转化成为16进制字符串
         * @param s
         * @return
         */
        public static String strTo16(String s) {
            String str = "";
            for (int i = 0; i < s.length(); i++) {
                int ch = (int) s.charAt(i);
                String s4 = Integer.toHexString(ch);
                str = str + s4;
            }
            return str;
        }
    }
    

    SerialPortUtil工具类

    public class SerialPortUtil {
    
        public static SerialPort serialPort = null;
        public static InputStream inputStream = null;
        public static OutputStream outputStream = null;
        public static Thread receiveThread = null;
        public static boolean flag = false;
    
        public static Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
            }
        };
    
        /**
         * 打开串口的方法
         */
        public static void openSrialPort(){
            Log.i("test","打开串口");
            try {
                serialPort = new SerialPort(new File("/dev/"+ IConstant.PORT),IConstant.BAUDRATE,0);
                //获取打开的串口中的输入输出流,以便于串口数据的收发
                inputStream = serialPort.getInputStream();
                outputStream = serialPort.getOutputStream();
                flag = true;
                receiveSerialPort();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
        /**
         *关闭串口的方法
         * 关闭串口中的输入输出流
         * 然后将flag的值设为flag,终止接收数据线程
         */
    
        public static void closeSerialPort(){
            Log.i("test","关闭串口");
            try {
                if(inputStream != null) {
                    inputStream.close();
                }
                if(outputStream != null){
                    outputStream.close();
                }
                flag = false;
            } catch (IOException e) {
                e.printStackTrace();
            }
    
        }
    
        /**
         * 发送串口数据的方法
         * @param data 要发送的数据
         */
        public static void sendSerialPort(String data){
            Log.i("test","发送串口数据");
            try {
                byte[] sendData = data.getBytes();
                outputStream.write(sendData);
                outputStream.flush();
                Log.i(TAG, "sendSerialPort: "+sendData);
                Log.i("test","串口数据发送成功");
            } catch (IOException e) {
                e.printStackTrace();
                Log.i("test","串口数据发送失败");
            }
        }
    
        /**
         * 接收串口数据的方法
         */
        public static void receiveSerialPort(){
            Log.i("test","接收串口数据");
            if(receiveThread != null)
                return;
            /*定义一个handler对象要来接收子线程中接收到的数据
                并调用Activity中的刷新界面的方法更新UI界面
             */
            final Handler handler = new Handler(){
                @Override
                public void handleMessage(Message msg) {
                    MainActivity.refreshTextView(msg.getData().getString("data"));
                }
            };
            /*创建子线程接收串口数据
             */
            receiveThread = new Thread(){
                @Override
                public void run() {
                    while (flag) {
                        try {
                            byte[] readData = new byte[1024];
                            if (inputStream == null) {
                                return;
                            }
                            int size = inputStream.read(readData);
                            if (size>0 && flag) {
                                String recinfo = new String(readData,0,size);
                                Log.i("test", "接收到串口数据:" + recinfo);
                                /*将接收到的数据封装进Message中,然后发送给主线程
                                 */
                                Message message = new Message();
                                Bundle bundle = new Bundle();
                                bundle.putString("data",recinfo);
                                message.setData(bundle);
                                handler.sendMessage(message);
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            };
            //启动接收线程
            receiveThread.start();
        }
    
    }
    

    SerialPort类

    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 {
                    //通过挂载到linux的方式,修改文件的操作权限
                    Process su = Runtime.getRuntime().exec("/system/xbin/su");
                    String cmd = "chmod 777 " + 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);
        }
    
        // Getters and setters
        public InputStream getInputStream() {
            return mFileInputStream;
        }
    
        public OutputStream getOutputStream() {
            return mFileOutputStream;
        }
    
        // JNI(调用java本地接口,实现串口的打开和关闭)
    /**串口有五个重要的参数:串口设备名,波特率,检验位,数据位,停止位
     其中检验位一般默认位NONE,数据位一般默认为8,停止位默认为1*/
        /**
         * @param path     串口设备的据对路径
         * @param baudrate 波特率
         * @param flags    校验位
         */
        private native static FileDescriptor open(String path, int baudrate, int flags);
        public native void close();
    
        static {//加载jni下的C文件库
            System.loadLibrary("serial_port");
        }
    }
    

    IConstant

    public interface IConstant {
        String PORT = "填写你那边需要连接的串口号";//串口号
        int BAUDRATE = ;//波特率
    }
    

    相关文章

      网友评论

          本文标题:安卓串口通讯发送指令代码详解

          本文链接:https://www.haomeiwen.com/subject/njveyftx.html