Unity串口通信 16进制 SerialPorts 设置COM口

简介: 串口通信,实时传输,设置COM口,打包程序可设置COM口

1. 新建Unity工程,在场景中建立两个GameObject,分别命名:SerialPorts;DataCtl(直接拖拽或查找DataCtl,代码中可自行修改)

2.新建两个C#脚本,分别命名:SerialPortScript;DataCtlScript,并分别挂载到上述两个游戏物体

3.在Assets文件夹中新建文件夹命名:streamingAssets;在streamingAssets文件夹中新建Text文件命名:PortNameConfig;

在PortNameConfig.txt中写入串口名字,例COM7  

4.SerialPortScript:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO.Ports;
using System.Threading;
using System.IO;
using UnityEngine.Video;
using System;
using System.Text;

public class PortTestScript : MonoBehaviour
{
    public string portName = " ";
    public int baudrate = 9600;
    public Parity parite = Parity.None;
    public int dataBits = 8;
    public StopBits stopbits = StopBits.One;
    SerialPort port;
    Thread portRev, portDeal;
    Queue <string> dataQueue;
    string outStr = string.Empty;

    void Start ()
    {
        //本地路径  
        string fileAddress = System.IO.Path.Combine (Application.streamingAssetsPath, "PortNameConfig.txt");  
    
    
        FileInfo fInfo0 = new FileInfo (fileAddress);  
        string s = "";  

        if (fInfo0.Exists) {  
            StreamReader r = new StreamReader (fileAddress);  
            s = r.ReadToEnd (); 
            portName = s;
            dataQueue = new Queue<string> (); 
            port = new SerialPort (portName, baudrate, parite, dataBits, stopbits);
            port.ReadTimeout = 400;
            try {
                port.Open ();
                Debug.Log ("串口打开成功!");
                portRev = new Thread (PortReceivedThread);
                portRev.IsBackground = true;
                portRev.Start ();
                portDeal = new Thread (DealData);
                portDeal.Start ();
            } catch (System.Exception ex) {
                Debug.Log (ex.Message);
            }
        }

    }


    //接收数据
    void PortReceivedThread ()
    {
        try {
            byte[] buf = new byte[1];
            string resStr = string.Empty; 
            if (port.IsOpen) {
                port.Read (buf, 0, 1);
            }
            if (buf.Length == 0) {
                return;
            }
            if (buf != null) {
                for (int i = 0; i < buf.Length; i++) {
                    //                    resStr += ASCIIEncoding.UTF8.GetString (buf);
                    resStr += buf [i].ToString ("X2") + " ";

                    //                    resStr += Encoding.UTF8.GetString (buf);
                    dataQueue.Enqueue (resStr); 
                    resStr += resStr;
                    //                    print (resStr); 

                }
            }
        } catch (System.Exception ex) {
//            Debug.Log (ex.Message);
        }
    }

    string message = " ";
    //处理
    void DealData ()
    {
        while (dataQueue.Count != 0) {
            for (int i = 0; i < dataQueue.Count; i++) {
                outStr += dataQueue.Dequeue ();

                if (outStr.Length == 24) {
                    
                    Debug.Log (outStr);
                    message = outStr;
                    outStr = string.Empty;
                }
            }
        }
    }


    public GameObject _shotctl;

    /// <summary>
    /// 传参数
    /// </summary>
    /// <param name="message"></param>
    void GetTheMessage (string message)
    {
        //传参数给 _shotctl这个游戏物体
        _shotctl.SendMessage ("GetShotMessage", message);

    }


    void SendData (byte[]msg)
    {
        //这里要检测一下msg
        if (port.IsOpen) {
            port.Write (msg, 0, msg.Length);
        }
    }

    string Info = " ";
    // Update is called once per frame
    void Update ()
    {
        if (port.IsOpen) {
            
        
            if (!portRev.IsAlive) {
                portRev = new Thread (PortReceivedThread);
                portRev.IsBackground = true;
                portRev.Start ();

            }
            if (!portDeal.IsAlive) {
                portDeal = new Thread (DealData);
                portDeal.Start ();
            } 
        }
        if (Info != message) {
            GetTheMessage (message);
            Info = message = " ";
        }
    }

    void OnApplicationQuit ()
    {
        Debug.Log ("退出!");
        if (port.IsOpen) {
            if (portRev.IsAlive) {
                portRev.Abort ();
            }
            if (portDeal.IsAlive) {
                portDeal.Abort ();
            }
        }

        port.Close ();
    }

}
 

5.DataCtlScript:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ctlScript : MonoBehaviour
{
    // Use this for initialization
    void Start ()
    {
        

    }
    // Update is called once per frame
    void Update ()
    {
            
    }
    public void GetShotMessage (string shotmessage)
    {
        //打印 shotmessage
        print(shotmessage);
        
    }

}
 

可以通过上述进行测试。

不过我也准备了UnityPakage包,可以直接下载Demo使用,地址:https://download.csdn.net/download/rick__/10764655

猜你喜欢

转载自blog.csdn.net/Rick__/article/details/83743294
今日推荐