Unity展厅项目相关的Unity串口

首先我自己写了一个串口类
PortControl`using UnityEngine;
using System.Collections;
using System.IO.Ports;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Text;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using LitJson;
using System.IO;

public class PortControl : MonoBehaviour
{

private static PortControl instance;
public static PortControl Instance
{
    get { return instance; }
}

#region 定义串口属性
// public GUIText gui;
//public GUIText Test;
//定义基本信息
public string portName = "";//串口名
public int baudRate =0;//波特率
public Parity parity = Parity.None;//效验位
public int dataBits = 8;//数据位
public StopBits stopBits = StopBits.One;//停止位
SerialPort sp = null;
public bool canRecieveMsg = true;//是否能接收发来的信息
Thread dataReceiveThread;

//发送的消息
private string message = " ";
public List<byte> listReceive = new List<byte>();
char[] strchar = new char[100];//接收的字符信息转换为字符数组信息
string str;
private JsonData Setting;
public double DaiJiTime;
#endregion
void Awake()
{
    OpenPort();
    dataReceiveThread = new Thread(new ThreadStart(PortReceive));
    dataReceiveThread.IsBackground = true;
    dataReceiveThread.Start();

    if (instance != null)
    {
        Destroy(gameObject);
        return;
    }
    instance = this;
    DontDestroyOnLoad(this.gameObject);
}


#region 创建串口,并打开串口
public void OpenPort()
{
    //创建串口
    if (sp == null)
    {
        Setting = JsonMapper.ToObject(File.ReadAllText(Application.dataPath + "/StreamingAssets/PortSetting.json"));
        portName = Setting["portName"].ToString();

        baudRate = (int)Setting["baudRate"];
        DaiJiTime = (double)Setting["SettingTime"];
        sp = new SerialPort(portName, baudRate, parity, dataBits, stopBits);
        sp.ReadTimeout = 500;
        sp.WriteTimeout = 500;
        try
        {
            sp.Open();
            Debug.Log("串口已经打开");
        }
        catch (Exception ex)
        {
            Debug.Log("打开信息错误" + ex.Message);
        }
    }
}
#endregion



#region 程序退出时关闭串口
void OnApplicationQuit()
{
    canRecieveMsg = false;
    ClosePort();
}
public void ClosePort()
{
    try
    {
        sp.Close();
        dataReceiveThread.Abort();
    }
    catch (Exception ex)
    {
        Debug.Log(ex.Message);
    }
}
#endregion


/// <summary>
/// 打印接收的信息
/// </summary>
void PrintData()
{
    for (int i = 0; i < listReceive.Count; i++)
    {
        strchar[i] = (char)(listReceive[i]);
        str = new string(strchar);
    }
    Debug.Log(str);//打印保存的信息
    listReceive.Clear();
}

#region 接收数据
void DataReceiveFunction()
{
    // 按单个字节发送处理信息,不能接收中文
    while (sp != null && sp.IsOpen)
    {
        Thread.Sleep(1);
        try
        {
            byte addr = Convert.ToByte(sp.ReadByte());
            sp.DiscardInBuffer();
            listReceive.Add(addr);
            PrintData();
        }
        catch
        {
            listReceive.Clear();
        }
    }
}


void PortReceive()
{

    try
    {
        while (canRecieveMsg)
        {

            Thread.Sleep(10);//这行是设定读取间隔,可以根据需要不使用
            if (!sp.IsOpen)
                return;
            int datalength = sp.BytesToRead;
            if (datalength == 0)
            {
                continue;
            }
            int i = 0;
            StringBuilder sb = new StringBuilder();
            while (i < datalength)
            {
                byte[] ds = new byte[1];
                int len = sp.Read(ds, 0, 1);
                sb.Append(Encoding.UTF8.GetString(ds, 0, len));
                i += len;
            }
            Debug.Log("获取串口之后的数据:"+sb.ToString());
          
        }
    }
    catch { }
}
#endregion






#region 发送数据
public void WriteData(string dataStr)
{
    if (sp.IsOpen)
    {
        sp.Write(dataStr);
        Debug.Log("往端口发送的数据是" + dataStr);
    }
}

public void WriteData(Byte[] dataStr)
{
    if(sp.IsOpen)
    {
        sp.Write(dataStr,0,8);
        Debug.Log("往端口发送的数据是" + dataStr);
    }
}



//void OnGUI()
//{

//    message = GUILayout.TextField(message);
//    if (GUILayout.Button("Send Input"))
//    {
//        WriteData(message);
//    }
//    string test = "AA BB 01 12345 01AB 0 ab";//测试字符串
//    if (GUILayout.Button("Send Test"))
//    {
//        WriteData(test);
     


//    }
//}
#endregion

}`
这个串口是向USB发送串口相关信号的

项目中也用到了分屏,实际上就是弄出来2个Camera来,然后
我自己写了1个类来区分分屏

public class ActiveDisplay : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
//Screen.SetResolution(1920, 1080, true);
Display.displays[0].Activate();
Display.displays[0].SetRenderingResolution(1920, 1080);
if (Display.displays[1] != null)
{
Display.displays[1].Activate();
Display.displays[1].SetRenderingResolution(1920, 1080);
}

}

}
读写Json文件里边的一个自己写的一个类
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using System.Text;
using LitJson;
using UnityEngine.UI;

public class JsonObjectModel
{
public List infoList{get;set;}
}
public class JsonArrayModel
{
public string Signal{get;set;}
public double Time{get;set;}
public byte[] Signalbyte { get; set; }

}

public class LoadJson : MonoBehaviour
{

public Button ButtonSend;
// Start is called before the first frame update
void Start()
{
    
    StreamReader streamreader = new StreamReader(Application.dataPath + "/StreamingAssets/Info.json");
    JsonReader js = new JsonReader(streamreader);//再转换成json数据

    JsonObjectModel jsonObject=JsonMapper.ToObject<JsonObjectModel>(js);
    foreach (var info in jsonObject.infoList)
    {
        Debug.Log(info.Signal + " " + info.Time + " ") ;

    }
    InitSendMsg(jsonObject);
   // byte[] bytes = new byte[] { 0xA1 };
    //StartCoroutine(SendMsgByTime(5.0, bytes));

    for(int i=0;i<jsonObject.infoList.Count;i++)
    {
        int k = i;
        StartCoroutine(SendMsgByTime(jsonObject.infoList[k].Time, jsonObject.infoList[k].Signalbyte));
    }

}

IEnumerator SendMsgByTime(double deltaTime,byte[] bytes)
{
    yield return new WaitForSeconds((float)deltaTime);
    PortControl.Instance.WriteOneByte(bytes);
}

private void InitSendMsg(JsonObjectModel model)
{
    for (int i = 0; i < model.infoList.Count; i++)
    {
        if (model.infoList[i].Signal == "A1")
            model.infoList[i].Signalbyte = new byte[] { 0xA1 };
        else if (model.infoList[i].Signal == "B1")
            model.infoList[i].Signalbyte = new byte[] { 0xB1 };
        else if (model.infoList[i].Signal == "C1")
            model.infoList[i].Signalbyte = new byte[] { 0xC1 };
        else if (model.infoList[i].Signal == "D1")
            model.infoList[i].Signalbyte = new byte[] { 0xD1 };
        else if (model.infoList[i].Signal == "A2")
            model.infoList[i].Signalbyte = new byte[] { 0xA2 };
        else if (model.infoList[i].Signal == "B2")
            model.infoList[i].Signalbyte = new byte[] { 0xB2 };
        else if (model.infoList[i].Signal == "C2")
            model.infoList[i].Signalbyte = new byte[] { 0xC2 };
        else if (model.infoList[i].Signal == "D2")
            model.infoList[i].Signalbyte = new byte[] { 0xD2 };

    }

}

// Update is called once per frame
void Update()
{
    
}

}

总结就差不多到这里了

猜你喜欢

转载自blog.csdn.net/charlsdm/article/details/122998606
今日推荐