C# Unity3D-连接到Arduino Uno的HC-05蓝牙模块:读取始终超时
我正在尝试使用一个连接到Arduino Uno的HC-05模块从IMU无线发送数据,作为Unity3D仿真的输入。我已经确认模块使用PuTTY工作,并且发送和接收正确。当我在unity中连接并尝试读取HC-05时,它总是超时。我已尝试将C# Unity3D-连接到Arduino Uno的HC-05蓝牙模块:读取始终超时,c#,unity3d,bluetooth,serial-port,C#,Unity3d,Bluetooth,Serial Port,我正在尝试使用一个连接到Arduino Uno的HC-05模块从IMU无线发送数据,作为Unity3D仿真的输入。我已经确认模块使用PuTTY工作,并且发送和接收正确。当我在unity中连接并尝试读取HC-05时,它总是超时。我已尝试将sp.ReadLine()更改为sp.Read(),以查看是否缺少换行符,但没有区别 这是统一代码 using System; using System.Text; using System.Collections; using System.IO.Ports;`
sp.ReadLine()
更改为sp.Read()
,以查看是否缺少换行符,但没有区别
这是统一代码
using System;
using System.Text;
using System.Collections;
using System.IO.Ports;`
using UnityEngine;
public class PlayerController : MonoBehaviour
{
private Rigidbody rb;
Vector3 origin,newPos;
SerialPort sp;
string text;
int trials = 0;
float speed;
void Start()
{
rb = GetComponent<Rigidbody>();
origin = rb.position;
sp = new SerialPort("\\\\.\\COM4", 9600);
if (!sp.IsOpen)
{
print("Opening COM4, baud 9600");
sp.Open();
sp.ReadTimeout = 100;
sp.Handshake = Handshake.None;
if (sp.IsOpen) { print("Open"); }
}
}
void reset()
{
rb.position = origin;
}
void Update()
{
string data;
float r = Input.GetAxis("Cancel");
Vector3 toPos=new Vector3();
if (!sp.IsOpen)
{ trials++;
sp.Open();
print(trials);
}
if (r != 0.0f)
{
reset();
}
if (sp.IsOpen)
{
//print("SP is OPEN");
data = sp.ReadLine();
sp.BaseStream.Flush();
//if (data != null) {
//print("data recieved");
text = data.ToString();
//float step = speed * Time.deltaTime;
//toPos.Set(data[6],data[7],data[8]);
//rb.rotation.SetLookRotation(toPos,rb.position);
//}
}
}
private void OnGUI()
{
text=GUI.TextField(new Rect(10, 10, 200, 20), text);
}
这是个例外
TimeoutException: The operation has timed-out.
System.IO.Ports.WinSerialStream.Read (System.Byte[] buffer, Int32 offset, Int32 count)
System.IO.Ports.SerialPort.read_byte ()
System.IO.Ports.SerialPort.ReadTo (System.String value)
System.IO.Ports.SerialPort.ReadLine ()
(wrapper remoting-invoke-with-check) System.IO.Ports.SerialPort:ReadLine ()
PlayerController.Update () (at Assets/PlayerController.cs:59)
我为这篇冗长的文章道歉,并感谢所有的帮助。
谢谢 是的,我解决了。这是一个愚蠢的错误。算了吧。 我的arduino在发送数据之前一直在等待我发送“b”,我在尝试更正另一个错误时删除了执行该操作的行。因此超时,因为没有数据可读取
ACCEL DATA------------------
X-Axis Accel -9665
Y-Axis Accel -11690
Z-Axis Accel -3847
GYRO DATA-------------------
X-Axis Gyro 177
Y-Axis Gyro 181
Z-Axis Gyro 130
MAG DATA--------------------
X-Axis Mag 118
Y-Axis Mag 418
Z-Axis Mag -176
TEMP DATA-------------------
Temp 1050
TimeoutException: The operation has timed-out.
System.IO.Ports.WinSerialStream.Read (System.Byte[] buffer, Int32 offset, Int32 count)
System.IO.Ports.SerialPort.read_byte ()
System.IO.Ports.SerialPort.ReadTo (System.String value)
System.IO.Ports.SerialPort.ReadLine ()
(wrapper remoting-invoke-with-check) System.IO.Ports.SerialPort:ReadLine ()
PlayerController.Update () (at Assets/PlayerController.cs:59)