【问题标题】:How to send and receive data via bluetooth BLE?如何通过蓝牙BLE发送和接收数据?
【发布时间】:2016-12-07 21:38:08
【问题描述】:

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

我目前正在使用蓝牙 BLE 设备,我想同时连接到 iOS 和 android,但我对如何通过蓝牙 BLE 正确地向设备发送和接收数据(字节 [])有点摸不着头脑。

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

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

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

我的连接功能,我通过其名称和 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)如果是,我如何将ICharacteristic 连接到设备为了通过蓝牙 BLE 发送和接收数据而发现的?

【问题讨论】:

  • 你在特征上试过StartUpdatesAsync()方法吗?这应该将您与阅读和写作的特征联系起来
  • @skar 啊好的,但我不需要以某种方式将我的 ICharacteristics 与我的设备连接吗? ICharacteristics 如何知道它将向哪个设备发送数据?还是当你连接到蓝牙时它会自动识别?

标签: c# arduino bluetooth-lowenergy


【解决方案1】:

如果您还没有这样做,请检查您的 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);

【讨论】:

  • 好的!非常感谢您的回答。解决了我的很多问题。我正在使用这个模块:ebay.com/itm/… 我将不得不阅读关于发送到这个特定设备的内容!但我猜这是一个特点。
猜你喜欢
  • 2015-04-21
  • 2021-08-16
  • 1970-01-01
  • 2014-06-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-02
相关资源
最近更新 更多