Unity3d 打开关闭串口

1、初始界面

 2、打开COM8

 3、向COM8发送数据

 4、关闭串口

 虚拟串口工具下载地址:

主要内容如下:

相机:MainCamera

下拉框:创建方法如下图

代码:

InitSerialPortDropdown.cs 

MenUI.cs

SerialPortManager.cs

using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

public class InitSerialPortDropdown : MonoBehaviour
{

    /// <summary>
    /// Dropdown-TextMeshPro
    /// </summary>
    public TMPro.TMP_Dropdown serialPortDropDown;

    public Camera _MainCamera = null;
    // Start is called before the first frame update
    void Start()
    {
        InitDropdown();
        
        //Vector3 localPosition=new Vector3(-Screen.width/2+25, 0,0);
        
        //serialPortDropDown.transform.SetLocalPositionAndRotation(localPosition, serialPortDropDown.transform.rotation);
    }

    // Update is called once per frame
    private void InitDropdown()
    {
        //清空默认节点
        serialPortDropDown.options.Clear();

        
        foreach (string serialPortName in SerialPortManager.GetPort())
        {
            //初始化
            TMP_Dropdown.OptionData op = new TMP_Dropdown.OptionData();
            op.text = serialPortName;
            serialPortDropDown.options.Add(op);
        }
    }
}
using System.Collections;
using System.Collections.Generic;
using TMPro;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.UI;

public class MenUI : MonoBehaviour
{
    public SerialPortManager serialPortManage;
    /// <summary>
    /// Dropdown-TextMeshPro
    /// </summary>
    public TMPro.TMP_Dropdown serialPortDropDown;
    // Start is called before the first frame update
    void Start()
    {
        //serialPortManage = new SerialPortManager();
        serialPortManage = gameObject.AddComponent<SerialPortManager>();
    }

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

    }

    void OnGUI()
    {

        if (serialPortManage.sp == null)
        {
            if (GUI.Button(new Rect(25, 25, 100, 30), "打开串口"))
            {
                Debug.Log(serialPortDropDown.options[serialPortDropDown.value].text);
                serialPortManage.portName = serialPortDropDown.options[serialPortDropDown.value].text;
                serialPortManage.OpenPort();
            }
        }
        else
        {
            if (GUI.Button(new Rect(25, 25, 100, 30), "关闭串口"))
            {
                serialPortManage.ClosePort();
                serialPortManage.sp = null;
            }
        }

        if (serialPortManage.sp!=null)
        {
            if (serialPortManage.sp.IsOpen)
            {
                if (GUI.Button(new Rect(130, 25, 100, 30), "发送数据"))
                {
                    serialPortManage.WriteData("HelloUnity");
                    Debug.Log("向串口发送HelloUnity");
                }


            }
        }


        if (GUI.changed)
        {

        }
    }
}

using UnityEngine;
using System.Collections;
using System.IO.Ports;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Text;
using Microsoft.Win32;
using UnityEngine.XR;

public class SerialPortManager : MonoBehaviour
{
    public string portName = "COM1";//串口号
    public int baudRate = 9600;//波特率
    public Parity parity = Parity.None;//效验位
    public int dataBits = 8;//数据位
    public StopBits stopBits = StopBits.One;//停止位
    public SerialPort sp = null;
    Thread dataReceiveThread;
    public List<byte> listReceive = new List<byte>();
    public char[] strchar = new char[100];//接收的字符信息转换为字符数组信息
    string str;

    public void Start()
    {
        //OpenPort();
        //dataReceiveThread = new Thread(new ThreadStart(DataReceiveFunction));
        //dataReceiveThread.Start();
    }


    public void OpenPort()
    {
        //创建串口
        sp = new SerialPort(portName, baudRate, parity, dataBits, stopBits);
        sp.ReadTimeout = 400;
        try
        {
            sp.Open();
            dataReceiveThread = new Thread(new ThreadStart(DataReceiveFunction));
            dataReceiveThread.Start();
        }
        catch (Exception ex)
        {
            Debug.Log(ex.Message);
        }
    }

    void OnApplicationQuit()
    {
        ClosePort();
    }

    public void ClosePort()
    {
        try
        {
            sp.Close();
            dataReceiveThread.Abort();
        }
        catch (Exception ex)
        {
            Debug.Log(ex.Message);
        }
    }

    private void Update()
    {
        PrintData();
    }

    //打印数据
    void PrintData()
    {
        if(listReceive.Count<=0)
        {
            //WriteData("你在吗?");
            return;
        }
        for (int i = 0; i < listReceive.Count; i++)
        {
            strchar[i] = (char)(listReceive[i]);
            str = new string(strchar);
        }
        Debug.Log(str);
    }

    //接收数据
    void DataReceiveFunction()
    {
        byte[] buffer = new byte[1024];
        int bytes = 0;
        while (true)
        {
            if (sp != null && sp.IsOpen)
            {
                try
                {
                    bytes = sp.Read(buffer, 0, buffer.Length);//接收字节
                    if (bytes == 0)
                    {
                        continue;
                    }
                    else
                    {
                        string strbytes = Encoding.Default.GetString(buffer);
                        //接受的数据
                        Debug.Log(strbytes);

                        buffer = new byte[1024];
                    }
                }
                catch (Exception ex)
                {
                    if (ex.GetType() != typeof(ThreadAbortException))
                    {
                    }
                }
            }
            Thread.Sleep(10);
        }
    }

    //发送数据
    public void WriteData(string dataStr)
    {
        if (sp.IsOpen)
        {
            sp.Write(dataStr);
        }
    }

    public static string[] GetPort()
    {
        try
        {
            RegistryKey hklm = Registry.LocalMachine;

            RegistryKey software11 = hklm.OpenSubKey("HARDWARE");

            //打开"HARDWARE"子健
            RegistryKey software = software11.OpenSubKey("DEVICEMAP");

            RegistryKey sitekey = software.OpenSubKey("SERIALCOMM");

            //获取当前子健
            String[] Str2 = sitekey.GetValueNames();

            //获得当前子健下面所有健组成的字符串数组
            int ValueCount = sitekey.ValueCount;
            //获得当前子健存在的健值
            int i;
            string[] rtn = new string[ValueCount];
            for (i = 0; i < ValueCount; i++)
            {
                rtn[i] = (string)sitekey.GetValue(Str2[i]);
            }
            return rtn;
        }
        catch (Exception e)
        {
            Debug.Log(e.Message);
            return null;
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

为风而战

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值