Search code examples
flutterarduinobluetoothbluetooth-lowenergyarduino-nano

Arduino Nano 33 BLE doesn't receive data sent via flutter app


import 'package:control_pad/control_pad.dart';
import 'package:flutter_reactive_ble/flutter_reactive_ble.dart';

final flutterReactiveBle = FlutterReactiveBle();
late QualifiedCharacteristic c;

Future<void> main() async {
  runApp(const MaterialApp(
    title: 'Control Pad Example',
    home: FirstRoute(),
  ));
}

class FirstRoute extends StatelessWidget {
  const FirstRoute({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('car'),
        actions: [
          IconButton(
            constraints: BoxConstraints.expand(width: 80),
            onPressed: () async {
              print("pressed");
              var serviceUuid =
                  Uuid.parse("0000180a-0000-1000-8000-00805f9b34fb");
              var characteristicUuid =
                  Uuid.parse("00002a57-0000-1000-8000-00805f9b34fb");
              var foundDeviceId = 'FB:DF:BF:CD:83:26';
              flutterReactiveBle.connectToDevice(id: foundDeviceId,
                connectionTimeout: const Duration(seconds: 5),
              ).listen((state) async {
                if (state.connectionState == DeviceConnectionState.connected) {
                  print("connected");
                  await flutterReactiveBle.requestConnectionPriority(deviceId: foundDeviceId, priority:  ConnectionPriority.highPerformance);
                  c = QualifiedCharacteristic(
                      serviceId: serviceUuid,
                      characteristicId: characteristicUuid,
                      deviceId: foundDeviceId);
                }
              });
            },
            icon: const Text("BLE", textAlign: TextAlign.center),
          ),
        ],
      ),
      body: JoystickView(
        onDirectionChanged: (double x, double y) async {
          print('$x, $y');

          flutterReactiveBle.writeCharacteristicWithoutResponse(c, value: [0x01]);
        },
      ),
    );
  }
}

I get the connection confirmation from Arduino but when trying to use writeCharacteristicWithoutResponse Arduino doesn't seem to receive anything. Using apps like LightBlue I can easily write hex inputs and Arduino receives them. I don't have much prior knowledge on Bluetooth and would like to understand what is it I'm missing here. Arduino code seems to be working well so the problem is on flutter apps side.


Solution

  • I could not get the code working with the package I was using. After changing to Flutter Blue and using this code, I was successful in writing and receiving data from the flutter app.

    async {
      flutterBlue.startScan(timeout: Duration(seconds: 4));
      var subscription =
          flutterBlue.scanResults.listen((results) async {
        for (int k = 0; k < results.length; k++) {
          ScanResult r = results[k];
          if (r.device.id.toString() == <YOUR_DEVICE_ID>) {
            print("found device");
            device = r.device;
            await device.connect();
            List<BluetoothService> services =
                await device.discoverServices();
            for (int j = 0; j < services.length; j++) {
              var service = services[j];
              if (service.uuid.toString() ==
                  <YOUR_SERVICE_UUID>) {
                print("found serial");
                var characteristics = service.characteristics;
                for (int i = 0; i < characteristics.length; i++) {
                  BluetoothCharacteristic c = characteristics[i];
                  if (c.uuid.toString() ==
                      <YOUR_CHARACTERISTIC_UUID>) {
                    print("found chars");
                    chars = c;
                  }
                }
              }
            }
          }
        }
      });
    }
    

    Here is a working but buggy Charasteristic finder. After this, you can send data with simple await chars.write([<hex-value>]);. This doesn't work without having responses turned on (they are automatically). If someone could explain this, that would be lovely.