当前位置: 首页 > news >正文

android compose 串口通信

1.添加依赖

implementation("io.github.xmaihh:serialport:2.1.1")

2.添加SerialHelper派生类

class SerialPortHelper(portName:String,baudRate:Int): SerialHelper(portName,baudRate) {var receivedDataBuffer = mutableListOf<Byte>()override fun onDataReceived(paraComBean: ComBean?) {if(paraComBean!=null){var temp:ByteArray = paraComBean.bRec;receivedDataBuffer.addAll(temp.toList())//receivedDataBuffer.addAll(paraComBean.toList())}}init {setStickPackageHelper (object : AbsStickPackageHelper {override fun execute(isStream: InputStream?): ByteArray? {try {val available = isStream?.available()if (available != null) {if (available > 0) {val buffer = ByteArray(available)val size = isStream.read(buffer)if (size > 0) {return buffer}} else {// 若没有数据,等待50毫秒Thread.sleep(50)}}} catch (e: IOException) {e.printStackTrace()} catch (e: InterruptedException) {e.printStackTrace()}return null}})}}

3.创建串口处理类

class SericalCommunicate {var serialPort:SerialPortHelper? = null//var outputSeriaPort = mutableStateOf("/dev/ttyS0")var serialportName:MutableState<String> = mutableStateOf("/dev/ttyS0")var serialBaud:MutableState<Int> = mutableStateOf(115200)init {initSerialport()}@OptIn(ExperimentalStdlibApi::class)fun initSerialport(){try {serialPort = SerialPortHelper(serialportName.value,serialBaud.value)//SerialPort(File(serialportName.value),serialBaud.value,'N',8,)}catch (e:Exception){e.printStackTrace()}GlobalScope.launch {val buffer = ByteArray(1024)while(serialPort!=null){val reader = serialPort!!.receivedDataBufferif(reader!=null) {var length = reader!!.sizeif (length>0){val data = String(buffer, 0, length)var dataStr = data.toByteArray().toHexString()Log.d("scoreInfo", dataStr)}serialPort!!.receivedDataBuffer.clear()}delay(50)}}}fun SetSerialPara(){reConnectedSerial()}fun reConnectedSerial(){if(serialPort!=null) {serialPort?.close()serialPort = null}initSerialport()}fun sendDataFromSerialport(data:ByteArray){if(serialPort!=null){serialPort!!.send(data)}}}

http://www.lryc.cn/news/517649.html

相关文章:

  • Cursor无限续杯——解决Too many free trials.
  • 网络传输层TCP协议
  • 我的前端面试笔记(React篇)
  • Qt 5.14.2 学习记录 —— 팔 QWidget 常用控件(3)
  • HTTP协议和WebSocket协议
  • 校园网断网自检测重链接
  • LAMP搭建
  • Sentinel-5P遥感数据下载及预处理教程【20250105】
  • 手写@MapperScan
  • 【C++】深入理解迭代器(Iterator)
  • 后端Java开发:第十二天
  • 记录一下Coding一直不能clone
  • LLM加速方法,Adapter Tuning和Prompt Tuning的区别及原理举例
  • 【SVN】版本发布快捷操作
  • GitLab 创建项目、删除项目
  • STM32-笔记37-吸烟室管控系统项目
  • VisionPro软件Image Stitch拼接算法
  • 【从零开始入门unity游戏开发之——unity篇09】unity6基础入门——Unity游戏对象和组件的本质、Unity中的反射机制
  • 【Linux】深入理解文件系统(超详细)
  • MoEs and Transformers 笔记
  • 在Linux中,如何禁用root用户直接SSH登录?
  • 用Python实现简单的任务自动化
  • 为AI聊天工具添加一个知识系统 之26 资源存储库和资源管理器
  • Windows10环境下安装RabbitMq折腾记
  • 对快速由表及里说拜拜/如何正确运用由表及里
  • spring mvc源码学习笔记之八
  • 探秘5网口IIOT网关
  • 左神算法基础巩固--5
  • Python的Matplotlib库应用(超详细教程)
  • 负载均衡服务器要怎么配置?