gpt4 book ai didi

c# - 从 Android 应用程序读取 Unity 中的串行数据

转载 作者:太空宇宙 更新时间:2023-11-03 10:42:05 25 4
gpt4 key购买 nike

我正在使用 Android 的 SensoDuino ( Official website ) 应用程序使用蓝牙串行通信将加速度计、陀螺仪等传感器数据发送到 PC 中的 Unity。我在 Unity 中使用以下代码接收数据 -

using UnityEngine;
using System.Collections;
using System.IO.Ports;
using System;

public class COM : MonoBehaviour {

public SerialPort sp;
public float data;

void Start () {
sp = new SerialPort("COM3", 9600,Parity.None, 8, StopBits.One);
Debug.Log ("Connection started");

if (sp != null)
{
if (sp.IsOpen)
{
sp.Close();
Debug.Log ("Closing port, because it was already open!");
}
else
{
sp.Open(); // opens the connection
// sets the timeout value before reporting error
sp.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
Debug.Log("Port Opened!");
}
}
else
{
if (sp.IsOpen)
{
print("Port is already open");
}
else
{
print("Port == null");
}
}

Debug.Log ("Open Connection finished running");
}

void Update () {
data = float.Parse( sp.ReadTo ("\r") ) ;
print ("data = " + data);
}

private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
SerialPort spl = (SerialPort)sender;
data = float.Parse( spl.ReadTo ("\r") ) ;
Debug.Log(data.ToString());
print ("data = " + data);
}
}

但是我无法接收到任何数据。 DataReceiveHandler 根本没有触发。我也尝试使用 ReadLine(),但它卡住了 Unity。

SensoDuino 发送加速度计数据的格式是

1,104,0.54437256,-0.2632141,9.826126

1,105,0.56111145,-0.279953,9.8524475

1,106,0.54556274,-0.2632141,9.833298

1,107,0.5515442,-0.26081848,9.841675

1,108,0.5312042,-0.2644043,9.867996

这是一个连续的流,可能是使用 ReadLine() 时卡住的原因。

请帮我读取数据。

最佳答案

我找到了解决方案。 ReadLine() 是一个阻塞调用,所以我不得不使用 ReadByte() 来连续读取字节并稍后转换数据。为了减少延迟,在线程中调用了 ReadByte() 函数。

 void recData() {
if ((sp != null) && (sp.IsOpen)) {
byte tmp;
string data = "";
string avalues="";
tmp = (byte) sp.ReadByte();
while(tmp !=255) {
data+=((char)tmp);
tmp = (byte) sp.ReadByte();
if((tmp=='>') && (data.Length > 30)){
avalues = data;
parseValues(avalues);
data="";
}
}
}
}

我做了一个很详细的教程here

关于c# - 从 Android 应用程序读取 Unity 中的串行数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31826646/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com