Unity3D SerialPort处理

Posted William Jiang

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Unity3D SerialPort处理相关的知识,希望对你有一定的参考价值。

using UnityEngine;
using System.Collections;
using System;
using System.Threading;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO.Ports;
using System.Text.RegularExpressions;
using System.Text;


public class UnitySerialPort : MonoBehaviour
{


    private SerialPort sp;
    private Queue queueDataPool;
    private Thread tPort;
    private Thread tPortDeal;
    private string strOutPool = string.Empty;
    string finalstring = string.Empty;
    string tempstring = string.Empty;

    byte flag0 = 0xAA;//start sign
    byte flag1 = 0x8E;//end sign

    List cmdList = null;//catch pre sign
     
    List<List> DataList = new List<List>();//catch all sign 
    // Use this for initialization 
    void Start()
    {
        sp = new SerialPort("COM3", 115200, Parity.None, 8, StopBits.One);
        if (!sp.IsOpen)
        {
            sp.Open();
        }
        tPort = new Thread(DealData);
        tPort.Start();
        tPortDeal = new Thread(ReceiveData);
        tPortDeal.Start();
    }


    // Update is called once per frame 
    void Update()
    {
        if (!tPortDeal.IsAlive)
        {
            tPortDeal = new Thread(ReceiveData);
            tPortDeal.Start();
        }
        if (!tPort.IsAlive)
        {
            tPort = new Thread(DealData);
            tPort.Start();
        }
    }


    private void ReceiveData()
    {
        try
        {
            Byte[] buf = new Byte[1];
            string sbReadline2str = string.Empty;
            if (sp.IsOpen) sp.Read(buf, 0, 1);
            if (buf.Length == 0)
            {
                return;
            }
            if (buf != null)
            {

                for (int i = 0; i < buf.Length; i++)
                {
                    if (buf[i] == flag0)
                    {
                        cmdList = new List();
                        cmdList.Add(buf[i]);
                    }
                    else if (buf[i] == flag1)
                    {
                        cmdList.Add(buf[i]);
                        DataList.Add(cmdList);
                    }
                    else
                    {
                        cmdList.Add(buf[i]);
                    }
                }

                if (DataList.Count > 0)
                {
                    List cmd = DataList[0];

                    StringBuilder sb = new StringBuilder();
                    for (int i = 0; i < cmd.Count; i++)
                    {
                        sb.Append(cmd[i] + " ");
                    }

                    Debug.Log(sb.ToString());

                    DataList.RemoveAt(0);
                }

            }
        }
        catch (Exception ex)
        {
            Debug.Log(ex);
        }
    }
    private void DealData()
    {
        while (queueDataPool.Count != 0)
        {
            for (int i = 0; i < queueDataPool.Count; i++)
            {
                strOutPool += queueDataPool.Dequeue();
                if (strOutPool.Length == 16)
                {
                    Debug.Log(strOutPool);
                    strOutPool = string.Empty;
                }
            }

        }
    }

    private void SendSerialPortData(string data)
    {
        if (sp.IsOpen)
        {
            sp.WriteLine(data);
        }
    }

    void OnApplicationQuit()
    {
        sp.Close();
    }

    void OnGUI()
    {
        if (GUILayout.Button("Send Data", GUILayout.Height(30)))
        {
            byte[] buffer = { 0xAA, 0x00, 0x22, 0x00, 0x00, 0x22, 0x8E };
            sp.Write(buffer, 0, buffer.Length);
        }

    }
}

 Unity3中使用SerialPort类进行串口通讯好像有bug,主要是在数据接收这一块,数据接收采用单独的线程来处理并缓存下来,然后再进行解析,经过测试prefect;

以上是关于Unity3D SerialPort处理的主要内容,如果未能解决你的问题,请参考以下文章

Unity3D软硬件Unity3D与串口通信 SerialPort类完全教程

出售 unity3d串口插件

在SerialPort.Close上C#Winform冻结

数据流和Promise Node.js与serialport

Node.js笔记:SerialPort(串口)模块使用

Android 串口通信