Android Studio USB串口通信

文章目录

概要

最近突然要Android环境中串口通信

流程

1:获取USB中的File名称

2:连接

3:发送数据

4:接受数据

技术名词解释

例如:

  • 波特
  • 端口
  • GPT-2
  • GPT-3
  • ChatGPT

技代码

  • API
  • 支持模型类型
    1:添加依赖
bash 复制代码
implementation 'com.licheedev:android-serialport:2.1.3'

2:获取所有的串口

bash 复制代码
 Vector<File> mDevices = null;
 public List<File> devFile=new ArrayList<>();
 //----------------------
if (mDevices == null) {
                mDevices = new Vector<File>();
                File dev = new File("/dev");

                File[] files = dev.listFiles();

                if (files != null) {v
                    int i;
                    for (i = 0; i < files.length; i++) {
                        if (files[i].getAbsolutePath().startsWith(mDeviceRoot)) {
                            Log.v(TAG, "device: " + files[i]);
                            devFile.add(files[i]);
                            mDevices.add(files[i]);
                        }
                    }
                }
            }

2:连接

bash 复制代码
import com.nfgk.xx.usb.utils.ByteUtil;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class SerialHelper {
    private static final String TAG="SerialHelper";
    private SerialPort mSeriaPort;
    private OutputStream mOutputStream;
    private InputStream mInputStream;
    private ReadThread mReadThread;
    // 打开串口
    public boolean open(String devicePath, int baudRate) {
        // 1. 检查设备节点是否存在
        File device = new File(devicePath);
        if (!device.exists()) {
            Log.e(TAG, "device is null:" + devicePath);
            return false;
        }

        try {
            //  打开串口(参数:设备、波特率、校验位等)
            // 第三个参数:0表示无校验,1表示奇校验,2表示偶校验
            mSeriaPort = new SerialPort(device, baudRate); //8, 0, 1, 0
            // 获取读写流
            mOutputStream = mSeriaPort.getOutputStream();
            mInputStream = mSeriaPort.getInputStream();

    
            mReadThread = new ReadThread();
            mReadThread.start();
            return true;
        } catch (IOException e) {
            Log.e(TAG, device+" open:" + e.getMessage());
            return false;
        }
    }

    private class ReadThread extends Thread {
        @Override
        public void run() {
            super.run();
            byte[] buffer = new byte[1024]; 
            int bytes;

            while (!isInterrupted() && mInputStream != null) {
                try {

                    bytes = mInputStream.read(buffer);
                    if (bytes > 0) {

                        byte[] data = new byte[bytes];
                        System.arraycopy(buffer, 0, data, 0, bytes);

                        onDataReceived(data);
                    }
                } catch (IOException e) {
                    Log.e(TAG, "error:" + e.getMessage());
                    break;
                }
            }
        }
    }

    // 数据接收回调(需在主线程处理)
    private void onDataReceived(byte[] data) {
        // 示例:转换为十六进制字符串
        String hexData = bytesToHex(data);
        Log.d(TAG, "收到数据:" + hexData);
        // 通知UI更新(可通过Handler或接口回调)
    }

    // 字节数组转十六进制字符串(便于调试)
    private String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            String hex = String.format("%02X ", b);
            sb.append(hex);
        }
        return sb.toString();
    }

    public void send(byte[] bOutArray) {
        try {
            if(mOutputStream==null)
            {
                Log.v(TAG,"mOutputStream is null");
                return;
            }
            this.mOutputStream.write(bOutArray);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void sendHex(String sHex) {
        byte[] outArray = ByteUtil.HexToByteArr(sHex);
        send(outArray);
    }

    public void sendTxt(String txt) {
        byte[] outArray = txt.getBytes();
        send(outArray);
    }
bash 复制代码
public class ByteUtil {
    public static int isOdd(int num) {
        return num & 0x1;
    }

    public static int HexToInt(String inHex) {
        return Integer.parseInt(inHex, 16);
    }

    public static byte HexToByte(String inHex) {
        return (byte) Integer.parseInt(inHex, 16);
    }

    public static String Byte2Hex(Byte inByte) {
        return String.format("%02x", new Object[]{inByte}).toUpperCase();
    }

    public static String ByteArrToHex(byte[] inBytArr) {
        StringBuilder strBuilder = new StringBuilder();
        int j = inBytArr.length;
        for (int i = 0; i < j; i++) {
            strBuilder.append(Byte2Hex(Byte.valueOf(inBytArr[i])));
            strBuilder.append("");
        }
        return strBuilder.toString();
    }

    public static String ByteArrToHex(byte[] inBytArr, int offset, int byteCount) {
        StringBuilder strBuilder = new StringBuilder();
        int j = byteCount;
        for (int i = offset; i < j; i++) {
            strBuilder.append(Byte2Hex(Byte.valueOf(inBytArr[i])));
        }
        return strBuilder.toString();
    }

    public static byte[] HexToByteArr(String inHex) {
        int hexlen = inHex.length();
        byte[] result;
        if (isOdd(hexlen) == 1) {
            hexlen++;
            result = new byte[hexlen / 2];
            inHex = "0" + inHex;
        } else {
            result = new byte[hexlen / 2];
        }
        int j = 0;
        for (int i = 0; i < hexlen; i += 2) {
            result[j] = HexToByte(inHex.substring(i, i + 2));
            j++;
        }
        return result;
    }
}
bash 复制代码
 serialHelper=new SerialHelper();
 String fileUsb=devFile;//"/dev/xxx"
boolean op= serialHelper.open(fileUsb,9600);
if(op)
   serialHelper.sendTxt("#0000");

小结

先上传代码

相关推荐
fundroid9 小时前
Android Studio + Gemini:重塑安卓 AI 开发新范式
android·android studio·ai编程
vortex510 小时前
谷歌黑客语法挖掘 SQL 注入漏洞
android·数据库·sql
-指短琴长-13 小时前
MySQL快速入门——基本查询(下)
android·mysql·adb
stevenzqzq14 小时前
android lambda回调
android
谢娘蓝桥15 小时前
Mac 安装 Xcode 及qt 环境安装
ide·macos·xcode
方知我15 小时前
使用VSCode进行SSH远程连接时无法与xxx建立连接
ide·vscode·ssh
重生之我要当编程大佬16 小时前
关于打不开pycharm的解决方法(一)
ide·python·pycharm
林北北的霸霸17 小时前
django初识与安装
android·mysql·adb
WarPigs18 小时前
Visual Studio笔记
ide·笔记·visual studio
Java 码农18 小时前
MySQL EXPLAIN 详解与优化指南
android·mysql·adb