如何在 flutter 中使用蓝牙发送/接收数据?

por*_*der 4 android arduino flutter

我正在尝试从 arduino uno 接收数据以及向 arduino uno 发送数据。我尝试过研究 flutter blue 插件和 flutter bluetooth 串行插件,flutter 串行插件似乎不完整,flutter blue 缺乏示例或文档,而且官方 github 示例太复杂,与我想做的事情无关。我想要一种非常简单的方法,使用 HC-05 模块从 arduino 发送或检索数据。

小智 5

如果您使用 HC-05 模块(无低功耗蓝牙)。使用“flutter_bluetooth_serial”包。它不是一个很好的包,但它应该可以工作。

这个例子可能不起作用。

扫描设备:

//Here the scan results will be saved
List<BluetoothDiscoveryResult> results = List<BluetoothDiscoveryResult>();

void startDiscovery() {
  streamSubscription = FlutterBluetoothSerial.instance.startDiscovery().listen((r) {
    results.add(r);
  });

  streamSubscription.onDone(() {
    //Do something when the discovery process ends
  });
}
Run Code Online (Sandbox Code Playgroud)

连接到设备:

从结果列表中选择设备时使用此功能。

BluetoothConnection connection;

connect(String address) async {
  try {
    connection = await BluetoothConnection.toAddress(address);
    print('Connected to the device');

    connection.input.listen((Uint8List data) {
      //Data entry point
      print(ascii.decode(data));
    })

  } catch (exception) {
    print('Cannot connect, exception occured');
  }
}
Run Code Online (Sandbox Code Playgroud)

发送数据:

Future send(Uint8List data) async {
    connection.output.add(data);
    await _connection.output.allSent;
}
Run Code Online (Sandbox Code Playgroud)

  • @Hamed Flutter_reactive_ble 不支持蓝牙&lt;5。我通过两台设备进行了发现测试。其中一个具有蓝牙 4.2,其他任何一个都使用蓝牙 5。结果是检测到唯一具有蓝牙 5 的设备。 (2认同)

Vin*_*ann 1

立即尝试 \xc2\xb4flutter_bluetooth_serial\xc2\xb4-package 中的示例应用程序。它们甚至包括从 HC-05 模块读取数据!如果您想要更简单的东西,请尝试从示例中提取基本代码并将其复制编码到另一个应用程序中。

\n