与Arduino的Windows 10 UWP蓝牙连接

时间:2016-12-29 01:15:35

标签: c# bluetooth arduino windows-10-universal windows-10-iot-core

我试图通过UWP应用程序找到通过蓝牙找到和连接Arduino的方法,所以有很多摆弄我找到了两种方法(不幸的是,找不到任何正式的MS文档) 所以一种方法是

            DeviceInformationCollection availableDevices = await BluetoothSerial.listAvailableDevicesAsync();
        foreach (DeviceInformation device in availableDevices)
        {
            deviceList.Add(device);

        }

这将返回名为" Dev B"的蓝牙设备,它实际上是我的arduino蓝牙模块。即使有其他设备可用配对/不配对,这种方法总是只返回" Dev B"。

然后我使用此功能连接Arduino

            var selectedDevice = (DeviceInformation)DeviceListView.SelectedItem;
        uint BaudRate = 9600;
        var connection = new BluetoothSerial(selectedDevice.Name);
        arduino = new RemoteDevice(connection);
        connection.begin(BaudRate, SerialConfig.SERIAL_8N1);
        connection.ConnectionEstablished += OnConnectionEstablished;

        ConnectedDeviceTextBox.Text = "Connected with Arduino.";

它工作得非常好,并且可以连接起来。到目前为止一切都很好

因为我需要找到所有可用的蓝牙设备,我发现了以下方法

            var selector = BluetoothDevice.GetDeviceSelectorFromPairingState(true);
        var devices = await DeviceInformation.FindAllAsync(selector);
        foreach (DeviceInformation device in devices)
        {
            deviceList.Add(device);
        }

这给了我所有配对的蓝牙设备,但蓝牙模块的名称现在是HC-05(这实际上是Windows在蓝牙设置和其他地方显示的名称)。但是如果我将此设备信息传递给上面的连接代码,它就不会连接。我尝试在

中使用设备名称
var connection = new BluetoothSerial(selectedDevice.Name);

但它不起作用,我也试过传入设备本身

var connection = new BluetoothSerial(selectedDevice);

仍然没有运气。

有人可以解释名称差异以及为什么它不与第二种方法连接。提前谢谢。

2 个答案:

答案 0 :(得分:2)

第一个api BluetoothSerial实际上在蓝牙的RFCOMM设备上运行。您可以找到它的实现here

第二个api BluetoothDevice实际上在蓝牙耳机等传统蓝牙设备上运行。

它们实现了不同的蓝牙协议,分别属于Windows运行时的Windows.Devices.Bluetooth.RfcommWindows.Devices.Bluetooth命名空间。

基于以上原因,您将BluetoothDevice传递给BluetoothSerial接口并失败,这是合理的。

至于设备名称,我认为因为它在调用两种类型的设备api的结果中有不同的表示,所以,它们是不兼容的。

答案 1 :(得分:0)

BluetoothSerial类调用RfcommDeviceService.FromIdAsync(String),其中字符串表示RFCOMM服务实例(服务)。

BluetoothDevice.FromIdAsync(String)采用代表经典基带(设备)的远程蓝牙设备实例的字符串。

如果您需要来自RfcommDeviceService的BluetoothDevice,请使用RfcommDeviceService.Device属性。

如果您想查找BluetoothDevice的服务,请使用BluetoothDevice.RfcommServices属性。

相关问题