unity脑电游戏的制作-脑电的获取步骤三

在unity中的代码

在unity工程中新建一个脚本,脚本中的代码如下:

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO.Ports;
using System.Threading;
using UnityEngine;
using UnityEngine.UI;
public class connect : MonoBehaviour
{
    public SerialPort COM = new SerialPort();//初始化serialport类的新实例,用于获取串行端口资源
    public Text PoorSignal;
    public Text Attention;
    public Text Meditation;
    void Start()
    {
        COM.BaudRate = 9600;//波特率
        COM.PortName = "COM3";//端口名
        COM.DataBits = 8;//数据位
        COM.ReadTimeout = 5000;
        COM.Open();//打开一个新的串行端口连接
       StartCoroutine(DataReceived());
       // COM.DataReceived += new SerialDataReceivedEventHandler(COM_DataReceived);
    }
    IEnumerator DataReceived()
    {
        while(true)
        {  
            Rec();
            yield return new WaitForSeconds(0.5f);
        }
    }
    /// <summary>
    /// 脑电的获取
    /// </summary>
 private void Rec()
    {
        try
        {
            int n = COM.BytesToRead;
            byte[] numArray = new byte[this.COM.BytesToRead];
            COM.Read(numArray, 0, n);
            if (numArray.Length == 0)
                return;
            else
            {
                Debug.Log("numarry长度是:" + numArray.Length);
            }
            if (numArray[0] == (byte)170 && numArray[1] == (byte)170)
            {
                Debug.Log("进入");
                if(numArray.Length==36)
                {
                    int num = 0;
                    num = Convert.ToInt32(numArray[4]);
                    Debug.Log("信号值是:" + num);
                   PoorSignal.text= num.ToString();

                    int attention = 0;
                    attention = Convert.ToInt32(numArray[32]);
                    Debug.Log("专注值是:" + attention);
                   Attention.text = attention.ToString();


                    int meditation = 0;
                    meditation= Convert.ToInt32(numArray[34]);
                    Debug.Log("放松值是:" + meditation);
                   Meditation.text = meditation.ToString();
                else
                {
                    return;
                }
            }
            COM.DiscardInBuffer();
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    public void ClosePort()
    {
        try
        {
            COM.Close();
        }
        catch(Exception ex)
        {
            Debug.Log(ex.Message);
        }
    }
    private void OnApplicationQuit()
    {
        ClosePort();
    }
}

运行时会出现的问题:
1.命名空间的引入:
在下面界面中选择程序包,安装using System.IO.Ports程序包。
unity脑电游戏的制作-脑电的获取步骤三
2.unity中需要进行相关的设置:
将Api Compatibility Level设置为4.0,相对应的命名空间才能正确引入。
unity脑电游戏的制作-脑电的获取步骤三
完成以上步骤,就可以从脑电设备中获取数据,并在unity中进行使用开发。

上一篇:LeetCode-303-区域和检索 - 数组不可变


下一篇:303. 区域和检索-数组不可变