Android串口使用方法
目录
前言
串口是一种用于android对硬件设备通信的一种协议,可以发送某种指令控制硬件设备,也可以接受传感器发送过来的数据,比如IC/ID卡,雷达,传感器等。下面介绍串口在android开发中的2使用方式
一、环境介绍
- Android
系统版本:Android 7.1 Android 12
Android Studio Electric Eel | 2022.1.1jdk-18.0.2
- PC
Windows11
串口调试工具sscom(或者其他串口调试工具也可以)
二、设备介绍
二、方法一:
使用ARMT自带的串口api SerialPort.java
1.引入库
在build.gradle 的dependencies中添加jar包
//ARMT SDK
implementation files('libs/armtsdkapi.jar')
2.编写代码
2.1初始化串口initSerialPort("/dev/ttyS4");
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编写接受数据
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
3发送数据
private void sendData() { try { if (mFileOutputStream3 != null) { mFileOutputStream3.write(mBuffer); } } catch (IOException e) { e.printStackTrace(); } }
以上就是通过ARMT提供的方法使用串口, 完整代码在最底部
三、方法二:
使用第三方库SerialPortHelper
1.引入库
在build.gradle 的dependencies中添加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发送数据
private void sendDataHelper() { if (mHelper != null && mHelper.isOpen()) { mHelper.sendTxtString("我是SerialPortHelper"); } }
2.3获取所有串口地址(通用方法)
List
allSerial = getAllSerial();
private List getAllSerial() { List 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 allSerial = getAllSerial(); Log.e("串口", "所有串口:" + allSerial); //初始化串口,串口地址:"/dev/ttyS4" initSerialPort("/dev/ttyS4"); //开启线程接收串口数据 readData(); //第二种使用串口的方式 mHelper = initSerialPortHelper("/dev/ttyS4"); //点击发送按钮 send.setOnClickListener(v -> { //点击模拟发送数据 sendData();// sendDataHelper(); }); } private List getAllSerial() { List 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; } 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(); } } 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 && 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
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341