标题 unity串口通信
前一段时间公司要求做unity串口通信,于是自己自学了下串口通信的东西,很简单
在这里插入代码片
```using System;
using System.Collections;
using System.Collections.Generic;
using System.IO.Ports;
using System.Text;
using System.Threading;
using System.Xml;
using UnityEngine;
public class RecieveSport : MonoBehaviour
{
public SerialPort port = null;
private Thread tPort = null;
private bool canRecieveMsg = true;
public static RecieveSport _instance;
public string message = "";
public List<byte> listReceive = new List<byte>();
string str;
char[] strchar = new char[100];//接收的字符信息转换为字符数组信息
public string comStr=“COM3”;//串口号
// Use this for initialization
void Awake()
{
}
void Start()
{
if (_instance == null)
{
_instance = this;
}
port = new SerialPort();
OpenPort(comStr);
transform.gameObject.AddComponent<GameController>();
}
// Update is called once per frame
void Update()
{
}
public bool OpenPort(string portName)
{
if (this.port != null && this.port.IsOpen == false)
{
try
{
this.port = new SerialPort(portName, 9600);
this.port.ReadTimeout = 500;
this.port.WriteTimeout = 500;
this.port.Open();
this.tPort = new Thread(new ThreadStart(PortReceive));
this.tPort.IsBackground = true;
this.tPort.Start();
return true;
}
catch (Exception err)
{
throw err;
}
}
else
{
throw new System.Exception("串口已经打开");
}
}
void OnApplicationQuit()
{
canRecieveMsg = false;
}
void PrintData()
{
for (int i = 0; i < listReceive.Count; i++)
{
strchar[i] = (char)(listReceive[i]);
str = new string(strchar);
}
Debug.Log(str);
listReceive.Clear();
}
/// <summary>
/// 可以读取多个字符,即字节数组;但是需要的平台的是.net 4.6
/// 将 Scripting Runing Vision 和Api Compatibility都改为.Net 4.6
/// </summary>
private void PortReceive()
{
try
{
while (canRecieveMsg)
{
Thread.Sleep(25);//这行是设定读取间隔,可以根据需要不使用
if (!port.IsOpen)
return;
int datalength = port.BytesToRead;
if (datalength == 0)
{
continue;
}
int i = 0;
StringBuilder sb = new StringBuilder();
while (i < datalength)
{
byte[] ds = new byte[1];
int len = port.Read(ds, 0, 1);
sb.Append(Encoding.UTF8.GetString(ds, 0, len));
i += len;
}
Debug.Log(sb.ToString());
message = sb.ToString();
//ProcessMsg(sb.ToString());
//这里sb就是串口获取的数据
}
}
catch { }
}
public void DataSend(string data)
{
port.Write(data);
}
//private void OnGUI()
//{
// string test = "woshinibaba";
// if (GUILayout.Button("SendMessage"))
// {
// DataSend(test);
// }
//}
}
## 标题串口通信