untiy串口通信

标题 unity串口通信

前一段时间公司要求做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;

public class RecieveSport : MonoBehaviour
{
    public SerialPort port = null;
    private Thread tPort = null;
    private bool canRecieveMsg = true;
    public static RecieveSport _instance;
    public string message = "";

    public List<byte> listReceive = new List<byte>();
    string str;
    char[] strchar = new char[100];//接收的字符信息转换为字符数组信息
    public string comStr=“COM3”;//串口号
    // Use this for initialization
    void Awake()
    {    
    }
    void Start()
    {
        if (_instance == null)
        {
            _instance = this;
        }
        port = new SerialPort();
        OpenPort(comStr);
        transform.gameObject.AddComponent<GameController>();

    }

    // Update is called once per frame
    void Update()
    {
    }
    public bool OpenPort(string portName)
    {
        if (this.port != null && this.port.IsOpen == false)
        {
            try
            {
                this.port = new SerialPort(portName, 9600);
                this.port.ReadTimeout = 500;
                this.port.WriteTimeout = 500;
                this.port.Open();

                this.tPort = new Thread(new ThreadStart(PortReceive));
                this.tPort.IsBackground = true;
                this.tPort.Start();
                return true;
            }
            catch (Exception err)
            {
                throw err;
            }
        }
        else
        {
            throw new System.Exception("串口已经打开");
        }
    }

    void OnApplicationQuit()
    {
        canRecieveMsg = false;
    }
    void PrintData()
    {
        for (int i = 0; i < listReceive.Count; i++)
        {
            strchar[i] = (char)(listReceive[i]);
            str = new string(strchar);
        }
        Debug.Log(str);
        listReceive.Clear();
    }
    /// <summary>
    /// 可以读取多个字符,即字节数组;但是需要的平台的是.net 4.6
    /// 将 Scripting Runing Vision 和Api Compatibility都改为.Net 4.6
    /// </summary>
    private void PortReceive()
    {

        try
        {
            while (canRecieveMsg)
            {

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

    public void DataSend(string data)
    {
        port.Write(data);
    }
    //private void OnGUI()
    //{
    //    string test = "woshinibaba";
    //    if (GUILayout.Button("SendMessage"))
    //    {
    //        DataSend(test);
    //    }
    //}
}

## 标题串口通信
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值