如何通过蓝牙BLE发送和接收数据?

时间:2016-12-07 21:38:09

标签: c# arduino bluetooth-lowenergy

我刚刚开始使用arduino / bluetooth,我现在正在寻找它并通过应用程序发送和接收命令。

我目前正在使用蓝牙BLE设备,我想连接到iOS和Android,但我正在摸索如何通过蓝牙BLE正确发送和接收数据(byte [])。

为了在应用程序和蓝牙/ arduino之间发送和接收信息,我使用ICharacteristic(我认为是通过BLE发送数据的正确接口),但我不确定我应该如何将它连接到我找到的设备。

我将展示我的代码,以便您清楚地看到我的意思。

public class bluetoothConnection
{
    public IAdapter thisAdapter { get; set; }
    public ICharacteristic thisCharacteristic {get; set;} 
}

我的connect-function,我通过名称和UUID连接到确切的设备。如果我找到了什么,那么我尝试发送数据的按钮将被启用并可用。

public async void connect()
{
    await myConnection.thisAdapter.StartScanningForDevicesAsync();

    myConnection.thisAdapter.DeviceDiscovered += async (sender, e) =>
    {
            if (e.Device.Id.ToString().Equals ("00001101 - 0000 - 1000 - 8000 - 00805f9b34fb" && e.Device.Name == "HC-05"))
            {
                await myConnection.thisAdapter.ConnectToDeviceAsync(e.Device);
                sendCommandButton.IsEnabled = true; //so my button is enabled and that function is below
            }
    };
}

所以如果我从我的arduino找到我的蓝牙设备,下面的按钮就会启用,现在我尝试将信息发送到我的arduino但是如何将thisCharacteristic连接到我刚才找到的设备上?

byte[] byteText = Encoding.UTF8.GetBytes("send this textline");

void sendCommandToArduino(object s, EventArgs e)
{
    myConnection.thisCharacteristic.WriteAsync(byteText);
}

这是我阅读以查看arduino是否向应用程序发送任何内容的方式:

var info = myConnection.thisCharacteristic.ReadAsync();
var result = info.Result;
string textresult = Encoding.UTF8.GetString(result);

我当然会把它放在while循环中以不断寻找数据。

所以我的问题是:为了通过蓝牙(应用程序和BLE设备)发送数据,我是否使用ICharacteristic(使用我当前使用的nuget),如果是,我如何连接{{1}我发现的设备是为了通过蓝牙BLE发送和接收数据?

1 个答案:

答案 0 :(得分:2)

如果您还没有这样做,请查看您的Arduino设备文档,了解您需要写入/读取的特性。特征将是特定服务的“孩子”。服务和特征都具有可用于引用它们的UUID。

在您的移动应用上,您应该在连接BLE设备时启动服务发现阶段。获得服务后,您可以搜索并获得对您的特征的引用。有点像:

var service = await connectedDevice.GetServiceAsync(Guid.Parse("<service-uuid-here>"));
var characteristic = await service.GetCharacteristicAsync(Guid.Parse("<characteristic-uuid-here>"));

// ...

characteristic.WriteAsync(message);
相关问题