C#串口通訊,單個字節接收

可以避免數據丟失,集成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;

/// <summary>
/// 注意!!!不要在主線程調用子線程的方法!!!
/// </summary>
public class SerialControl: MonoBehaviour
{
    public static SerialControl instance;
    public byte[] bytes = new byte[10];
    public SerialPort port;
    private Thread PortReceiveThread;
    Thread OpenPortThread;

    public SerialControl _instance
    {
        get
        {
            if (instance == null)
            {
                instance = this;
            }
            return instance;
        }
    }


    // Use this for initialization
    void Start()
    {
        port = new SerialPort();
        if (OpenPortThread != null)
        {
            OpenPortThread.Abort();
        }
        OpenPortThread = new Thread(OpenPort);
        OpenPortThread.Start();

    }

    void OpenPort()
    {
        if (this.port != null && this.port.IsOpen == false)
        {
            try
            {
                port = new SerialPort("COM" + GameData.Config.com, 57600);
                port.ReadTimeout = 500;
                port.WriteTimeout = 500;
                port.Open();
                if (PortReceiveThread != null)
                {
                    PortReceiveThread.Abort();
                }
                PortReceiveThread = new Thread(new ThreadStart(Receive));
                PortReceiveThread.IsBackground = true;
                PortReceiveThread.Start();
            }
            catch (Exception err)
            {
                Debug.Log(err);
                ClosePort();

                Thread.Sleep(3000);
                if (OpenPortThread != null)
                {
                    OpenPortThread.Abort();
                }
                OpenPortThread = new Thread(OpenPort);
                OpenPortThread.Start();

            }
        }
        else
        {
            Debug.Log("opened.");
        }
    }

    void OnApplicationQuit()
    {
        ClosePort();
    }

    void Receive()
    {
        Thread.Sleep(3000);
        try
        {
            while (true)
            {
                Thread.Sleep(25);
                if (!port.IsOpen)
                    return;
                int datalength = port.BytesToRead;
                if (datalength == 0)
                {
                    continue;
                }
                int i = 0;

                while (i < datalength)
                {
                    byte[] ds = new byte[1];
                    int len = port.Read(ds, 0, 1);
                    i += len;
                    if (i < bytes.Length)
                    {
                        bytes[i - 1] = ds[0];
                    }
                }

                for (int j = 0; j < bytes.Length; j++)
                {
                    if (bytes[j] == 202 && j < bytes.Length - 1)
                    {
                        if (bytes[j+1] <= GameData.Steps.end && bytes[j+1] >= GameData.Steps.begin)
                        {
                            GameData.trigger.Enqueue(bytes[j+1]);
                        }
                    }
                }
            }
        }
        catch(Exception ex)
        {
            Debug.Log(ex.Message);
            ClosePort();
            Thread.Sleep(3000);

            if (OpenPortThread != null)
            {
                OpenPortThread.Abort();
            }
            OpenPortThread = new Thread(OpenPort);
            OpenPortThread.Start();
        }
    }

    void Send(string data)
    {
        port.Write(data);
    }

    void ClosePort()
    {
        try
        {
            port.Close();
            if (PortReceiveThread != null)
            {
                PortReceiveThread.Abort();
            }

            if (OpenPortThread != null)
            {
                OpenPortThread.Abort();
            }

            Debug.Log("Serial Port close");
        }
        catch (Exception ex)
        {
            Debug.Log("Serial Port Close fail!:" + ex.Message);
        }
    }

}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章