【Unity3d】读取串口数据

最近搞了个读取串口数据的小程序:把相关硬件插到电脑usb口,通过硬件上的按钮操作unity3d(pc端)应用 。

 private void OpenPort(string portName, int baudRate, int dataBits, int readTimeout)
    {
        _mySerialPort = new SerialPort(portName);
        _mySerialPort.BaudRate = baudRate;
        _mySerialPort.DataBits = dataBits;
        _mySerialPort.StopBits = StopBits.One;
        _mySerialPort.Parity = Parity.None;
        _mySerialPort.ReadTimeout = readTimeout;
        //_mySerialPort.DataReceived//在unity环境下无效,需要协程
        StopCoroutine(DataReceivedCoroutine());
        StartCoroutine(DataReceivedCoroutine());
        try
        {
            _mySerialPort.Open();
        }
        catch(Exception e)
        {
            UnityEngine.Debug.Log(e.ToString());
        }
    }
private System.Collections.IEnumerator DataReceivedCoroutine()
    {
        byte[] dataBytes = new byte[SLOT_ARR_COUNT];//存储数据
        UnityEngine.WaitForSeconds wfs = new WaitForSeconds(Time.deltaTime);
        while (true)
        {
            if (_mySerialPort != null && _mySerialPort.IsOpen)
            {
                try
                {
                    int bytesToRead = _mySerialPort.BytesToRead;
                    if (bytesToRead > 0)
                    {
                        int len = _mySerialPort.Read(dataBytes, 0, bytesToRead);
                        CalBytesToLong(dataBytes, len);//把串中读取到的数据,解析成自己要的格式
                    }
                }
                catch (Exception ex)
                {
                    Debug.Log(ex.Message);
                }
            }
            yield return wfs;
        }
    }
private long CalBytesToLong(List<byte>bytes, int count)
    {
        long result = 0;
        bytes.Reverse();
        for (int i = 0; i < count && i < SLOT_COUNT; i++)
        {
            byte b = bytes[i];
            if (i == 0)
            {
                result += b;
            }
            else
            {
                if (b > 0)
                {
                    result |= (long)(b << (i * SLOT_COUNT));
                }
            }
        }
        return result;
    }
 private void ClosePort()
    {
        if(_mySerialPort!=null)
        {
            _mySerialPort.Close();
            _mySerialPort = null;
        }
    }

猜你喜欢

转载自blog.csdn.net/PangNanGua/article/details/114856382