unity基础开发----unity串口通信
来源:互联网 发布:js给html元素赋值 编辑:程序博客网 时间:2024/05/21 06:57
using UnityEngine;using System.Collections;using System.IO.Ports;using System;using System.Collections.Generic;using System.Threading;public class PortControl : MonoBehaviour {public GUIText gui; //定义基本信息public string portName = "COM2";public int baudRate = 9600;public Parity parity = Parity.None;public int dataBits = 8;public StopBits stopBits = StopBits.One;int[] data = new int[6];//用于存储6位数据SerialPort sp = null;Thread dataReceiveThread; //发送string message = ""; //byte[] message=new byte[8];void Start(){OpenPort();dataReceiveThread = new Thread(new ThreadStart(DataReceiveFunction));dataReceiveThread.Start();}void Update(){string str = "";for(int i=0; i<data.Length; i++){str += data[i].ToString() + " ";}gui.text = str; Debug.Log(str);}public void OpenPort(){sp = new SerialPort(portName, baudRate, parity, dataBits, stopBits);sp.ReadTimeout = 400;try{sp.Open();}catch(Exception ex){Debug.Log(ex.Message);}}public void ClosePort(){try{sp.Close();}catch(Exception ex){Debug.Log(ex.Message);}}public void WriteData(string dataStr){if(sp.IsOpen){sp.Write(dataStr);}}void OnApplicationQuit(){ClosePort ();}void DataReceiveFunction(){byte[] buffer = new byte[128];int bytes = 0; //定义协议int flag0 = 0xFF;int flag1 = 0xAA;int index = 0;//用于记录此时的数据次序while (true){if (sp != null && sp.IsOpen){try{bytes = sp.Read(buffer, 0, buffer.Length);for(int i=0; i<bytes; i++){if(buffer[i]==flag0 || buffer[i]==flag1){index = 0;//次序归0 continue;}else{if(index>=data.Length)index = data.Length-1;//理论上不应该会进入此判断,但是由于传输的误码,导致数据的丢失,使得标志位与数据个数出错data[index] = buffer[i];//将数据存入data中index++;}}}catch (Exception ex){if (ex.GetType() != typeof(ThreadAbortException)){Debug.Log(ex.Message);}}}Thread.Sleep(10);}}void OnGUI(){message = GUILayout.TextField(message);if(GUILayout.Button("Send Message")){WriteData(message);} string by= "XX AA 03 31 20 51 00 00"; if (GUILayout.Button("Send",GUILayout.Height(50))) { WriteData(by); }}}
0 0
- unity基础开发----unity串口通信
- Unity串口通信
- unity串口通信
- 基于Unity串口通信的解决方案
- Unity开发之Socket通信
- unity基础开发--shader基础知识
- unity基础开发-photon服务器
- unity基础开发--学习笔记
- 谷歌 CardBoard Unity开发基础
- unity C#脚本开发基础
- unity开发:Qt C++与unity之间TCP网络通信
- unity开发:Qt C++与unity之间UDP网络通信
- [Unity基础]unity备忘录
- Unity之串口通信(基于三姿态传感器)
- unity 基础
- unity基础
- Unity 基础
- unity基础开发----Unity镜面反射简易制作
- org.eclipse.birt.report.data.oda.jdbc.JDBCException: Missing properties in Connection.open(Propertie
- 于23种设计模式的有趣见
- 设计模式总结
- luogu1638
- linux 设置用户id 设置组id
- unity基础开发----unity串口通信
- 网站首页被K如何24小时内恢复
- 使用CocoaPods来做iOS程序的包依赖管理
- Asp编码优化技巧8则
- VS2012新建项目出错:未找到与约束ContractName Microsoft.VisualStudio.Text.ITextDocumentFactoryService
- ++前置和后置的区别
- Jianbo Shi 的博客-图像分割目标跟踪(CVPR)
- “大数据处理技术-基于hadoop的实战”四月北京班今日开课!
- 第七周作业3 -- 最长递增子序列