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

Unity3d使用SerialPortUtilityPro读取串口数据

Unity3d2021.3.35f1,Serial Port Utility Pro v2.6

一、测试串口接收基本功能

1.新建工程,导入Serial Port Utility Pro v2.6.unitypackage

提示 error CS0619: 'AndroidSdkVersions.AndroidApiLevel21' is obsolete: 'Minimum supported Android API level is 22 (Android 5.1 Lollipop). Please use AndroidApiLevel22 or higher'

解决方法将21改为22

2.打开ExampleDeviceList场景

3.修改DeviceListProgram波特率为115200,编辑代码SPUPDeviceList.cs

(1)将按钮名改为串口名

(2)接收0x00时不要丢弃,处理16进制时有用,

4.切换到SerialPortUtilityPro.cs,去掉ReadUpdate函数中的调试输出代码

5.添加byte数组以16进制字符串显示函数

        /// <summary>/// byte[]转16进制格式string/// </summary>/// <param name="bytes"></param>/// <returns></returns>public static string ToHexString(byte[] bytes){string returnStr = "";if (bytes != null){for (int i = 0; i < bytes.Length; i++){ returnStr += bytes[i].ToString("X2") + " ";}}return returnStr;}

6.输入16进制字符串

                string debugString = ToHexString(dataBuffer.ToArray());Debug.Log(debugString);SerialDebugAddString(debugString, false);

注意:程序UI字符串太长的话会被截断,输出到Unity控制台不会被截断。

二、在下拉列表中打开串口

1.修改SPUPDeviceList.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System;
using System.Linq;public class SPUPDeviceList : MonoBehaviour
{//SPUPList<SerialPortUtility.SerialPortUtilityPro> spList = new List<SerialPortUtility.SerialPortUtilityPro>();public int baudrate = 115200;public SerialPortUtility.SerialPortUtilityPro.OpenSystem openMode = SerialPortUtility.SerialPortUtilityPro.OpenSystem.USB;public PositioningManager positioningManager;public Dropdown dropdownDevices;public Button btnOpen;public Text textPrompt;private Dictionary<string, SerialPortUtility.SerialPortUtilityPro.DeviceInfo> dictIndex2Dev = new Dictionary<string, SerialPortUtility.SerialPortUtilityPro.DeviceInfo>();void Awake(){SerialPortUtility.SerialPortUtilityPro.DeviceInfo[] devicelist = SerialPortUtility.SerialPortUtilityPro.GetConnectedDeviceList(openMode);if (devicelist == null)return;foreach (SerialPortUtility.SerialPortUtilityPro.DeviceInfo d in devicelist){//serialPort = new SerialPortUtility.SerialPortUtilityPro(); //do not useString GameObjectName = "NONE";if (openMode == SerialPortUtility.SerialPortUtilityPro.OpenSystem.USB)GameObjectName = d.PortName;else if (openMode == SerialPortUtility.SerialPortUtilityPro.OpenSystem.BluetoothSSP)GameObjectName = d.SerialNumber;else if (openMode == SerialPortUtility.SerialPortUtilityPro.OpenSystem.PCI)GameObjectName = d.Vendor;dictIndex2Dev.Add(GameObjectName, d);}dropdownDevices.AddOptions(dictIndex2Dev.Keys.ToList());}private void Start(){btnOpen.onClick.AddListener(Open);}void Open(){string key = dropdownDevices.options[dropdownDevices.value].text;if(dictIndex2Dev.ContainsKey(key)){SerialPortUtility.SerialPortUtilityPro.DeviceInfo d = dictIndex2Dev[key];OpenSerialPort(d, key);}}private void OpenSerialPort(SerialPortUtility.SerialPortUtilityPro.DeviceInfo d, string GameObjectName){GameObject obj = new GameObject(GameObjectName);SerialPortUtility.SerialPortUtilityPro serialPort = obj.AddComponent<SerialPortUtility.SerialPortUtilityPro>();//configserialPort.SetDebugConsoleMonitorView(false);serialPort.OpenMethod = openMode;serialPort.VendorID = d.Vendor;serialPort.ProductID = d.Product;serialPort.SerialNumber = d.SerialNumber;serialPort.BaudRate = baudrate;   //115200kbpsserialPort.ReadProtocol = SerialPortUtility.SerialPortUtilityPro.MethodSystem.Streaming;serialPort.RecvDiscardNull = false;serialPort.IsAutoOpen = true;serialPort.OnReceveDistanceMsgHand += OnReceveDistanceMsg;spList.Add(serialPort);StartCoroutine(delayGetOpenResult(serialPort));}IEnumerator delayGetOpenResult(SerialPortUtility.SerialPortUtilityPro serialPort){yield return new WaitForSeconds(0.2f);bool suc = serialPort.IsOpened();textPrompt.text = suc ? "打开成功" : "打开失败";}void OnReceveDistanceMsg(uint dis1, uint dis2, uint dis3){positioningManager.UpdateDistance(dis1, dis2, dis3);}void OnDestory(){foreach (SerialPortUtility.SerialPortUtilityPro item in spList){item.Close();}}// Update is called once per framevoid Update (){if (Input.GetKey(KeyCode.Home) || Input.GetKey(KeyCode.Escape) || Input.GetKey(KeyCode.Menu)){Application.runInBackground = false;Application.Quit();return;}}//for public void ReadComprateString(object data){var text = data as string;Debug.Log(text);}
}

http://www.dtcms.com/a/354911.html

相关文章:

  • Linux(一) | 初识Linux与目录管理基础命令掌握
  • Libvio 访问异常排查指南
  • 2021/07 JLPT听力原文 问题一 2番
  • 【python】@staticmethod装饰器
  • nginx 配置文件初识全局块、events、http、server、location 的层级关系
  • SDK、JDK、JRE、JVM的区别
  • JSON 快速上手:语法解析与应用实例
  • 【VSCode】使用VSCode打开md文件以及转化为PDF
  • 打工人日报#20250828
  • HTTP 分块传输编码:深度解析与报文精髓
  • 第21节:环境贴图与PBR材质升级——构建电影级真实感渲染
  • Java 实现HTML转Word:从HTML文件与字符串到可编辑Word文档
  • 腕上智慧健康管家:华为WATCH 5与小艺的智美生活新范式
  • 使用EasyExcel实现Excel单元格保护:自由锁定表头和数据行
  • mac电脑双屏显示时程序坞跑到副屏的解决方法
  • 吱吱企业通讯软件以安全为基,搭建高效的通讯办公平台
  • ckman部署的clickhouse,节点迁移
  • 微算法科技(NASDAQ:MLGO)推出创新型混合区块链共识算法,助力物联网多接入边缘计算
  • [论文阅读] 人工智能 + 软件工程 | 告别“隐藏陷阱”:领域预训练模型SmartBERT如何赋能智能合约安全
  • MyBatis题
  • AR培训系统:油气行业的安全与效率革新
  • List<Map<String, String>>最简单的遍历方式
  • 在Ubuntu中安装配置MySql Server
  • [光学原理与应用-320]:光学产品不同阶段使用的工具软件、对应的输出文件
  • 计算机考研408《数据结构》真题模拟——数据结构与算法基本概念
  • DQN(深度Q网络):深度强化学习的里程碑式突破
  • Java 线程池拒绝策略
  • vscode pyqt5设置
  • 基于SpringBoot的老年人健康数据远程监控管理系统【2026最新】
  • JavaSE——八股文