目录

前言

 一、环境介绍

二、设备介绍

二、方法一:

1.引入库       

2.编写代码

三、方法二:

1.引入库       

2.编写代码

四、完整代码:

五、源码:



前言

串口是一种用于android硬件设备通信的一种协议,可以发送某种指令控制硬件设备,也可以接受传感器发送过来的数据比如IC/ID卡,雷达传感器等。下面介绍串口在android开发中的2使用方式


 一、环境介绍

系统版本:Android 7.1 Android 12 
Android Studio Electric Eel | 2022.1.1

jdk-18.0.2

  • PC

Windows11 
串口调试工具sscom(或者其他串口调试工具也可以)

二、设备介绍

二、方法一:

使用ARMT自带的串口api   SerialPort.java

1.引入库       

build.gradledependencies添加jar

//ARMT SDK
implementation files(‘libs/armtsdkapi.jar‘)

2.编写代码

2.1初始化串口
initSerialPort("/dev/ttyS4");
    /**
     * 初始化串口
     *
     * @param path 串口路径
     */
    private void initSerialPort(String path) {
        try {
            uart3 = new SerialPort(path, 9600, 8, "n", 1);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //获取输出mFileOutputStream3 = (FileOutputStream) uart3.getOutputStream();
        //获取输入mFileInputStream3 = (FileInputStream) uart3.getInputStream();
    }

2.2编写接受数据

/**
     * 开机线程接收串口数据
     * 收到数据后发送的Handler刷新
     */
    private void readData() {
        new Thread(() -> {
            while (run_flag) {
                int size3 = 0;
                try {
                    size3 = mFileInputStream3.read(mRevBuffer3);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (size3 > 0) {
                    String str3 = new String(mRevBuffer3, 0, size3);
                    Log.i("串口", "receiveData() --> " + str3);
                    mHandler.sendMessage(mHandler.obtainMessage(1, str3));
                    Arrays.fill(mRevBuffer3, (byte) 0x0);
                }
            }
        }, "串口接收线程").start();
    }

这里开启线程一直读数据,读到数据后通过Handler更新到Textview

2.3发送数据

/**
     * 发送串口数据
     */
    private void sendData() {
        try {
            if (mFileOutputStream3 != null) {
                mFileOutputStream3.write(mBuffer);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

以上就是通过ARMT提供的方法使用串口, 完整代码在最底部

三、方法二:

使用第三方库SerialPortHelper

1.引入库       

build.gradledependencies中添加jar

    //串口
    implementation 'com.github.maybesix:Android-XHLibrary:v1.0.0'

添加maven 仓库

 repositories {

        maven { url 'https://jitpack.io' }
       
    }

2.编写代码

2.1初始化串口
mHelper = initSerialPortHelper("/dev/ttyS4");

这里初始化 SerialPortHelper,并且设置监听, 收到数据后通过Handler更新TextView

 private SerialPortHelper initSerialPortHelper(String port) {
        SerialPortHelper serialPort = new SerialPortHelper(port, 9600);
        serialPort.setSerialPortReceivedListener(new SerialPortHelper.OnSerialPortReceivedListener() {
            @SuppressLint("SetTextI18n")
            @Override
            public void onSerialPortDataReceived(ComPortData comPortData) {
                String dataStr = comPortData.getRecTime() + " 收到: " + new String(comPortData.getRecData());
                mHandler.sendMessage(mHandler.obtainMessage(1, dataStr));
            }
        });
        serialPort.open();
        return serialPort;
    }

2.2发送数据

  private void sendDataHelper() {
        if (mHelper != null && mHelper.isOpen()) {
            mHelper.sendTxtString("我是SerialPortHelper");
        }
    }

 2.3获取所有串口地址(通用方法)

List<File> allSerial = getAllSerial();
 /**
     * 获取所有串口
     *
     * @return
     */
    private List<File> getAllSerial() {
        List<File> serialPorts = new ArrayList<>();
        Pattern pattern = Pattern.compile("^ttyS|^ttyUSB|^ttyACM|^ttyAMA|^rfcomm|^tty[^/]*$");
        File devDirectory = new File("/dev");

        File[] files = devDirectory.listFiles();
        if (files != null) {
            for (File file : files) {
                String name = file.getName();
                if (pattern.matcher(name).find()) {
                    serialPorts.add(file);
                    Log.e("串口", "扫描到的串口" + file);
                }
            }
        }
        return serialPorts;
    }

四、完整代码:

package com.armt.sdktest_armt.serialPort;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.armt.sdktest_armt.R;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;

import cn.com.armt.sdk.hardware.SerialPort;
import top.maybesix.xhlibrary.serialport.ComPortData;
import top.maybesix.xhlibrary.serialport.SerialPortHelper;

public class SerialPortActivity extends AppCompatActivity {

    private byte[] mRevBuffer3 = new byte[100];
    private byte[] mBuffer = "12345".getBytes();//{1,2,3,4,5};
    private SerialPort uart3;
    private FileOutputStream mFileOutputStream3;
    private FileInputStream mFileInputStream3;
    private boolean run_flag = true;
    private Button send;
    private TextView content;
    private SerialPortHelper mHelper;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_serial_port);

        send = findViewById(R.id.send);
        content = findViewById(R.id.content);

        //获取全部串口
        List<File> allSerial = getAllSerial();
        Log.e("串口", "所有串口:" + allSerial);

        //初始化串口,串口地址:"/dev/ttyS4"
        initSerialPort("/dev/ttyS4");
        //开启线程接收串口数据
        readData();

        //第二种使用串口的方式
        mHelper = initSerialPortHelper("/dev/ttyS4");

        //点击发送按钮
        send.setOnClickListener(v -> {
            //点击模拟发送数据
                sendData();
//            sendDataHelper();
        });
    }

    /**
     * 获取所有串口
     *
     * @return
     */
    private List<File> getAllSerial() {
        List<File> serialPorts = new ArrayList<>();
        Pattern pattern = Pattern.compile("^ttyS|^ttyUSB|^ttyACM|^ttyAMA|^rfcomm|^tty[^/]*$");
        File devDirectory = new File("/dev");

        File[] files = devDirectory.listFiles();
        if (files != null) {
            for (File file : files) {
                String name = file.getName();
                if (pattern.matcher(name).find()) {
                    serialPorts.add(file);
                    Log.e("串口", "扫描到的串口" + file);
                }
            }
        }
        return serialPorts;
    }

    /**
     * 初始化串口
     *
     * @param path 串口路径
     */
    private void initSerialPort(String path) {
        try {
            uart3 = new SerialPort(path, 9600, 8, "n", 1);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //获取输出流
        mFileOutputStream3 = (FileOutputStream) uart3.getOutputStream();
        //获取输入流
        mFileInputStream3 = (FileInputStream) uart3.getInputStream();
    }

    private Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            if (msg.what == 1) {
                String data = (String) msg.obj;
                content.append(data + "n");
            }
        }
    };

    /**
     * 发送串口数据
     */
    private void sendData() {
        try {
            if (mFileOutputStream3 != null) {
                mFileOutputStream3.write(mBuffer);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 开机线程接收串口数据
     * 收到数据后发送的Handler刷新
     */
    private void readData() {
        new Thread(() -> {
            while (run_flag) {
                int size3 = 0;
                try {
                    size3 = mFileInputStream3.read(mRevBuffer3);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (size3 > 0) {
                    String str3 = new String(mRevBuffer3, 0, size3);
                    Log.i("串口", "receiveData() --> " + str3);
                    mHandler.sendMessage(mHandler.obtainMessage(1, str3));
                    Arrays.fill(mRevBuffer3, (byte) 0x0);
                }
            }
        }, "串口接收线程").start();
    }


    /******************************第二种串口使用方式**********************************/


    private SerialPortHelper initSerialPortHelper(String port) {
        SerialPortHelper serialPort = new SerialPortHelper(port, 9600);
        serialPort.setSerialPortReceivedListener(new SerialPortHelper.OnSerialPortReceivedListener() {
            @SuppressLint("SetTextI18n")
            @Override
            public void onSerialPortDataReceived(ComPortData comPortData) {
                String dataStr = comPortData.getRecTime() + " 收到: " + new String(comPortData.getRecData());
                mHandler.sendMessage(mHandler.obtainMessage(1, dataStr));
            }
        });
        serialPort.open();
        return serialPort;
    }

    private void sendDataHelper() {
        if (mHelper != null &amp;&amp; mHelper.isOpen()) {
            mHelper.sendTxtString("我是SerialPortHelper");
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            run_flag = false;
            if (mFileOutputStream3 != null) mFileOutputStream3.close();
            if (mFileInputStream3 != null) mFileInputStream3.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        if (mHelper != null) {
            mHelper.close();
        }
    }
}

 五、源码下载地址:

完整源码


原文地址:https://blog.csdn.net/qaz96801/article/details/130424895

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任

如若转载,请注明出处:http://www.7code.cn/show_47828.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注