Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I send/receive data using bluetooth in flutter?

I'm trying to receive and send data from and to an arduino uno. I've tried looking into flutter blue plugin and flutter bluetooth serial plugin ,flutter serial plugin seems to be incomplete and flutter blue lacks examples or documentation, and the official github example is way too complicated and is irrelevant to what i want to do. I want a very simple method of sending or retrieving data from an arduino using a HC-05 module.

like image 892
portableCoder Avatar asked Mar 02 '23 22:03

portableCoder


2 Answers

If you are working with a HC-05 module (No Low Energy Bluetooth). Use ´flutter_bluetooth_serial´ package. It is not a great package, but it should work.

This example may not work.

Scan for devices:

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

Connect to device:

Use this function when you select a device from the result list.

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

Send data:

Future send(Uint8List data) async {
    connection.output.add(data);
    await _connection.output.allSent;
}
like image 158
Martin Olivari Avatar answered Mar 05 '23 17:03

Martin Olivari


Try the example app from the ´flutter_bluetooth_serial´-package now. They even included reading data from an HC-05-module! If you want something simpler, try extracting the essential code from the example and copycoding it into another app.

like image 40
Vincent Guttmann Avatar answered Mar 05 '23 16:03

Vincent Guttmann