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

10

我正在尝试从Arduino Uno接收和发送数据。我已经尝试了Flutter Blue插件和Flutter Bluetooth Serial插件,但是Flutter Serial插件似乎不完整,而Flutter Blue缺乏示例或文档,官方GitHub示例过于复杂,与我的需求无关。我想要一个非常简单的方法,使用HC-05模块发送或检索从Arduino获取的数据。


你好 @portablecoder,三年过去了,你找到了任何替代品吗?我是一个新手,想了解如何通过蓝牙发送和接收数据,有没有好的示例链接或博客可以学习? - amit.flutter
2个回答

11

如果您正在使用 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
  });
}

连接设备:

当您从结果列表中选择一个设备时,请使用此功能。

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');
  }
}

发送数据:

Future send(Uint8List data) async {
    connection.output.add(data);
    await _connection.output.allSent;
}

1
Flutter的更新版本不被支持,我建议使用这个包flutter_reactive_ble: ^3.1.1。 - Hamed
2
@Hamed Flutter_reactive_ble不支持蓝牙<5。我已经通过两个设备进行了测试。其中一个设备具有蓝牙4.2,其他任何设备都使用蓝牙5。结果只检测到具有蓝牙5的设备。 - Bcktr
@Bcktr,你在两年后找到其他选择了吗?我是一个新手,对于如何通过蓝牙发送和接收数据,我能否得到更多信息? - amit.flutter

1

现在可以尝试来自´flutter_bluetooth_serial´包的示例应用程序。他们甚至包括从HC-05模块读取数据!如果您想要更简单的东西,请尝试从示例中提取基本代码并将其复制到另一个应用程序中。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接