4

So I'm working in Unity3D, programming in C#, and I heard that one can read data from a Bluetooth adaptor via SerialPort. I have several Bluetooth USB adaptors that I've tried to connect on my PC using this method. However, when I try to open the SerialPort, I get an error message that says port does not exist. I only included the code relevant to the question, but portI is a string ("COM11" or "COM12") and PortIn is of type SerialPort.

void OnGUI() {
    GUI.Label(new Rect(btnX, btnY, btnW, btnH), "PortIn = " + portI);
    if(!connected) {
        for (int i = 0; i<ports.Length; i++) {
            if(GUI.Button(new Rect(btnX, btnY + btnH + (btnH * i), btnW, btnH), ports[i])) {
                portI = ports[i];
            }
        }           
    }       
    if(GUI.Button(new Rect(btnX + (btnW * 2 + 20), btnY, btnW, btnH), "Connect")) {
        portIn = new SerialPort(portI, 9600);               
        portIn.ReadTimeout = 1000;
        if (!portIn.IsOpen) {
            portIn.Open();
        }
        connected = true;
        }
    }       
}
4

2 回答 2

2

这是我正在处理的一些代码,只要 COM 端口(在我的情况下为 COM9)与配对时的蓝牙设备相同,它就会从蓝牙连接获取数据到独立的 PC 构建(或在编辑器中)它。

配对后,转到蓝牙设置 > COM 端口,查看带有设备名称的端口。它可能会说 COM8 或 COM9 或其他。如果设备已配对并且代码中的 COM 端口与蓝牙设置中的相同,并且超时数和波特率与您发送数据的应用程序中的相同......那么您将获得运行此代码时的某些内容。这只是为了帮助通过蓝牙连接到串行连接。

希望它可以帮助某人。通过阅读这些论坛,我得到了很多很好的建议;)

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

public class checker : MonoBehaviour {

    public static SerialPort sp = new SerialPort("COM9", 9600, Parity.None, 8, StopBits.One);
    public string message, message1;
    public string message2;

    void Start() {
        OpenConnection();   
    }

    void Update() { 
        message2 = sp.ReadLine(); 
    } 

    void OnGUI()    {
        GUI.Label(new Rect(10, 180, 100, 220), "Sensor1: " + message2);
    }

    public void OpenConnection() {
        if (sp != null) 
        {
            if (sp.IsOpen) 
            {
                sp.Close();
                message = "Closing port, because it was already open!";
            }
            else 
            {
                sp.Open(); 
                sp.ReadTimeout = 1000;  
                message = "Port Opened!";
            }
        }
        else 
        {
            if (sp.IsOpen)
            {
                print("Port is already open");
            }
            else 
            {
                print("Port == null");
            }
        }
    }

    void OnApplicationQuit() {
        sp.Close();
    }

}
于 2013-05-12T00:03:06.807 回答
1

这应该是可能的。蓝牙 rfcomm/spp 服务模拟串行端口。一个 COM 端口(如果它在 Windows 上)。波特率在这个仿真中并不重要,它总是尽可能快。

您需要将设备配对并连接。你连接的是什么设备?尝试先与 Putty 或某些终端应用程序建立连接。

于 2013-04-25T11:46:03.490 回答