2

I'm doing an iot project that need to communicate with arduino to gather some temperature information and pass it from serial communication through HM-10 to mobile app.

The app will request for the data and then arduino will transmit the data through HM-10.

I was able to connect to HM-10 and send commands to arduino using Flutter-blue dependency via characteristics. But unable to gather data from the arduino board even it transmit the data. Even I read the characteristics through flutter_blue the data does not show.

I want to know as we can write data via Bluetooth how we can get and read data too. (as characteristics.read() won't work)

It will be a huge help if someone can answer the issue.

Following is the code that used to communicate with HM-10.

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:flutter/services.dart';
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:flutter_blue/flutter_blue.dart';
import 'package:rxdart/rxdart.dart';

class BluetoothService with ChangeNotifier {
  final FlutterBlue flutterBlue = FlutterBlue.instance;

  late String connectionText;

  Future<bool> get bluetoothState => enabled();

  Future<bool> enabled() async {
    return await flutterBlue.isOn;
  }

  late StreamSubscription scanSubscription;
  String targetDeviceName = 'BT05';
  late BluetoothCharacteristic? targetCharacteristic;
  late BluetoothDevice _targetDevice;
  BluetoothDevice get targetDevice => _targetDevice;
  bool isDone = true;
  Stream streamScreen =
      ValueConnectableStream(FlutterBlue.instance.state).autoConnect();

  startScan() {
    connectionText = "Start Scanning";
    print(connectionText);

    scanSubscription =
        flutterBlue.scan(timeout: Duration(seconds: 4)).listen((scanResult) {
      print(scanResult);
      if (scanResult.device.name == targetDeviceName) {
        stopScan();
        connectionText = "Found Target Device";
        print(connectionText);
        _targetDevice = scanResult.device;
        notifyListeners();
        connectToDevice();
      }
    }, onDone: () {
      isDone = false;
      print('is done $isDone');
      stopScan();
      notifyListeners();
    });
    notifyListeners();
  }

  stopScan() {
    scanSubscription.cancel();
    flutterBlue.stopScan();
    print("stopped");
  }

  connectToDevice() async {
    connectionText = "Device Connecting";
    print(connectionText);

    await _targetDevice.connect();
    isDone = true;
    connectionText = "Device Connected";
    print(connectionText);
    discoverServices();
  }

  String uuid = "0000ffe0-0000-1000-8000-00805f9b34fb";
  String writeUuid = "0000ffe1-0000-1000-8000-00805f9b34fb";
  

  discoverServices() async {
    var services = await _targetDevice.discoverServices();
    services.forEach(
      (service) {
        if (service.uuid.toString() == uuid) {
          service.characteristics.forEach((characteristic) {
            if (characteristic.uuid.toString() == writeUuid) {
              targetCharacteristic = characteristic;

              print("All Ready with ${targetDevice.name}");
            }
          });
        }
      },
    );
  }

  readData() async {
    // _targetDevice.discoverServices().then((services) async {
    //   List<int> decode = await services[2].characteristics[0].read();
    //   print(decode);
    //   String msg = utf8.decode(decode);
    //   print(msg);
    // });
    targetCharacteristic!.value.listen(null).onData((data) {
      String msg1 = utf8.decode(data);
      print("here is the $msg1");
    });
    List<int> decode = await targetCharacteristic!.read();
      String msg = utf8.decode(decode);
      print(msg);
  }

  disconnectFromDevice({required BluetoothDevice device}) async {
    await device.disconnect();

    connectionText = "Device Disconnected";
    print(connectionText);
    notifyListeners();
  }

  writeData(String data) async {
    if (targetCharacteristic == null) return;

    List<int> bytes = utf8.encode(data);
    print("bytes recieved");

    await targetCharacteristic!.write(bytes, withoutResponse: false);
  }
}

Following is the arduino code.

char inputdata = 0;  //Variable for storing received data

void setup()
{
    Serial.begin(9600);                      //Sets the baud rate for bluetooth pins                     
   
}

void loop()
{

   if(Serial.available() > 0)      // Send data only when you receive data:
   {
      inputdata = Serial.read();        //Read the incoming data & store into data

      // If a measurement is required, measure data and send it back
      if ( inputdata == 't'){

          int t = 32;
          int m =7200;
          String data = (String(t)+','+String(m));
          Serial.print(data);

      }else if(inputdata == 'g') {
         
        String temp = "32";
        Serial.print(temp);
       
      } 
   }
}

0 Answers0