我刚刚开始使用arduino/蓝牙,现在我希望使用它,并通过一个应用程序发送和接收命令。
我目前正在使用一个蓝牙BLE设备,我想连接到iOS和安卓系统,但我有点想知道如何通过蓝牙BLE正确地发送和接收数据(byte[])到设备上。
为了在应用程序和蓝牙/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);
当然,我会把它放在一个data循环中,以便不断地查找数据。
因此,我的问题是:为了通过蓝牙(app和BLE设备)发送数据,我是否使用ICharacteristic
(与我使用的当前nuget一起使用),如果是的话,如何将ICharacteristic
连接到我找到的设备,以便通过蓝牙BLE发送和接收数据?
发布于 2016-12-08 08:30:44
如果您还没有这样做,请检查您的Arduino设备文档,看看您需要写入/读取哪个特性。一个特点将是一个特定服务的“孩子”。服务和特性都有UUID,您可以使用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);
https://stackoverflow.com/questions/41027839
复制