SerialPort串口通信(二)

简化版的串口通信,非常的简单,看了以后,会很简洁,很清晰,本人亲测,这个博客的例子完美运行

好吧,来看看如何使用SerialPort串口通信

1.首先我们来看一下,运行的效果图:

SerialPort串口通信(二)_第1张图片

2.添加依赖,在app下的builder.gradle

  //gogle serialPort
    implementation 'com.aill:AndroidSerialPort:1.0.8'

3.下发和接收数据:

package com.example.administrator.testz;


import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.TextViewCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.aill.androidserialport.SerialPort;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;


/**
 * Created by jiang on 2017/12/28.
 */

public class SerialportTestAct extends AppCompatActivity implements View.OnClickListener {
    private StringBuffer seriapPortMsg = new StringBuffer();
    private final String TAG = "SerialportTestAct:";
    private InputStream mInputStream;
    private OutputStream mOutputStream;
    private TextView log;
    private EditText serMsg;
    private Button sendMsg;
    private SerialPort serialPort;
    private final String SERIALPORT_NO3 = "/dev/ttyS1";//串口号3
    private final int BAUDRATE = 115200;//波特率
    private Context mContext;

    //记住  我们的程序  不管客户端还是硬件端 发送和接收的指令统一使用十六进制(HEX)来表示
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        setContentView(R.layout.act_serialport);
        log = (TextView) findViewById(R.id.log);
        sendMsg = (Button) findViewById(R.id.sendMsg);
        sendMsg.setOnClickListener(this);
        serMsg = (EditText) findViewById(R.id.serMsg);
        initSerialPort();  //初始化串口设置
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.sendMsg:
                //点击按钮向串口下发指令数据
                String msg = serMsg.getText().toString().trim();
                if(msg!=null&&!msg.equals("")){
                    //string转16进制的数据,下发的数据必须为byte数组,长度会根据协议来定
                    byte[] buff = fromHexString(msg);
                    try {
                        mOutputStream.write(buff,0,buff.length);
                        Log.e(TAG, "下发完成");
                    } catch (IOException e) {
                        e.printStackTrace();
                        Log.e(TAG, e.getMessage());
                    }
                }
        }
    }

    private void initSerialPort() {
        try {
            serialPort = new SerialPort(new File(SERIALPORT_NO3), BAUDRATE, 0);
            mInputStream = serialPort.getInputStream();
            mOutputStream = serialPort.getOutputStream();
            //这个地方为什么要开线程? 因为这个线程是用于监听返回的数据的,必须开,一直开着
            new Thread(new ReadSerialPortMsgThread()).start();
        } catch (Exception e) {
            e.printStackTrace();
            Log.e(TAG, "打开串口失败");
        }
    }

    //接收硬件通过串口回应的数据
    private class ReadSerialPortMsgThread implements Runnable {
        @Override
        public void run() {
            int size;
            byte buff[] = new byte[1024];
            while (true) {
                try {
                    if (mInputStream == null) {
                        return;
                    }
                    size = mInputStream.read(buff);
                    Log.e(TAG, "接收到串口回调w == " + size);
                    if (size > 0) {
                        for (int i = 0; i < size; i++) {
                            Log.e("TAG", "十进制=" + buff[i]);
                            final String res = hexToDecimal(buff[i]);
                            log.post(new Runnable() {
                                @Override
                                public void run() {
                                   // editIn.append(text)
                                    log.append("" + res);
                                }
                            });
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    //十进制转16进制
    private String hexToDecimal(byte oneByte) {
        String str = "";
        int h = (oneByte >>> 4) & 0xF;
        int l = oneByte & 0xF;
        char ch = (char) ((h < 10) ? ('0' + h) : ('A' + h - 10));
        char cl = (char) ((l < 10) ? ('0' + l) : ('A' + l - 10));
        str = "";
        str += ch;
        str += cl;
        return str;
    }

    /**
     * 16进制字符串转换成字节数组。
     * 

* param hex 16进制字符串 *这个协议是 还的重订 * @return 字节数组 */ private byte[] hexStringToByte(String hex) { if (hex == null || hex.equals("")) return null; String[] arry = hex.split(" "); byte[] data = new byte[arry.length]; try { for (int i = 0; i < arry.length; i++) { //这个地方在定协议 if (arry[i].length() > 2) return null; int d = Integer.parseInt(arry[i], 16); data[i] = (byte) (d & 0xff); } } catch (Exception e) { return null; } return data; } public static byte[] fromHexString(String hexString) { if (null == hexString || "".equals(hexString.trim())) { return new byte[0]; } byte[] bytes = new byte[hexString.length() / 2]; // 16进制字符串 String hex; for (int i = 0; i < hexString.length() / 2; i++) { // 每次截取2位 hex = hexString.substring(i * 2, i * 2 + 2); // 16进制-->十进制 bytes[i] = (byte) Integer.parseInt(hex, 16); } return bytes; } }

4.贴一下布局吧,仅仅一个类,就解决串口数据通信的下发和接收问题,到这里基本就结束了




    

    

    

    

    

 

你可能感兴趣的:(android,学习)