在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程序包。
将Api Compatibility Level设置为4.0,相对应的命名空间才能正确引入。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。