skip to Main Content

I’m using flutter for my mobile application. I want to connect my mobile app with Arduino using HC-05 module.

My flutter code (a small piece of code out of a big code):

class HomeLayout extends StatefulWidget {
  const HomeLayout({super.key});
  @override
  State<HomeLayout> createState() => _HomeLayout();
}

class _HomeLayout extends State<HomeLayout> {
void _scanDevices() async {
    List<BluetoothDevice> devices = <BluetoothDevice>[];
    print('scan started');
    try {
      devices = await FlutterBluetoothSerial.instance.getBondedDevices();
    } catch (ex) {
      print("Error: $ex");
    }
    print('scan ended');
    print(devices);
    for (BluetoothDevice device in devices) {
      print(device.address); // This will print the MAC address of each bonded device
    }
  }


  Future<bool> _connectToBluetooth() async {
    //_scanDevices();
    print('nnConnecting to the device');
    String address='my hc05 mac address';
    try {
        connection = await BluetoothConnection.toAddress(address);
      } catch(ex){
        print("Error : $ex");
        return false;
      }
    print('Connected to the device');
    return true;
    //receiveData();
  }

  void receiveData() async{
    bool check = await _connectToBluetooth();
    print("nnReceiving Data");
    if(check) {
      List<int> _dataBuffer = <int>[];
      connection!.input!.listen((Uint8List data) {
        setState(() {
          _dataBuffer.addAll(data);
          print("Data : " + data.toString());
        });
      });
    }
    print("Received Data");
  }

Widget build(BuildContext context) {
    receiveData();
... 
}
}

My arduino code:

SoftwareSerial mySerial(10, 11);

void setup(){
mySerial.begin(38400);
}

void loop(){
  int sound_sensor = analogRead(A1);
  light_sensor = analogRead(A0);
  mySerial.write("light sensor : ");
  mySerial.write(light_sensor);
  mySerial.write("sound sensor : ");
  mySerial.write(sound_sensor);
}

When I run my flutter code, it asks for Location (as to scan the available bluetooth devices).

My HC-05 module blinks as usual when i power my arduino and HC-05 (in red and blue colour). Then after 2/3 seconds, blue light disappears. then after a while, both the lights are on (doesn’t blink).

And my flutter code returns an error:

 PlatformException(connect_error, read failed, socket might closed or timeout, read ret: -1, java.io.IOException: read failed, socket might closed or timeout, read ret: -1
I/flutter (25783):  at android.bluetooth.BluetoothSocket.readAll(BluetoothSocket.java:845)
I/flutter (25783):  at android.bluetooth.BluetoothSocket.readInt(BluetoothSocket.java:859)
I/flutter (25783):  at android.bluetooth.BluetoothSocket.connect(BluetoothSocket.java:436)
I/flutter (25783):  at io.github.edufolly.flutterbluetoothserial.BluetoothConnection.connect(BluetoothConnection.java:57)
I/flutter (25783):  at io.github.edufolly.flutterbluetoothserial.BluetoothConnection.connect(BluetoothConnection.java:64)
I/flutter (25783):  at io.github.edufolly.flutterbluetoothserial.FlutterBluetoothSerialPlugin$FlutterBluetoothSerialMethodCallHandler.lambda$onMethodCall$4$io-github-edufolly-flutterbluetoothserial-FlutterBluetoothSerialPlugin$FlutterBluetoothSerialMethodCallHandler(FlutterBluetoothSerialPlugin.java:1007)
I/flutter (25783):  at io.github.edufolly.flutterbluetoothserial.FlutterBluetoothSerialPlugin$FlutterBluetoothSerialMethodCallHandler$$ExternalSyntheticL

Kindly help me to figure out why this error occurs and a way to get rid of it.

2

Answers


  1. try this one

    class HomeLayout extends StatefulWidget {
    const HomeLayout({Key? key}) : super(key: key);
    
    @override
    _HomeLayoutState createState() => _HomeLayoutState();
    }
    
    class _HomeLayoutState extends State<HomeLayout> {
    late BluetoothConnection _connection;
    List<int> _dataBuffer = [];
    
    @override
    void initState() {
    super.initState();
    _initBluetooth();
    }
    
    void _initBluetooth() async {
    // Initialize Bluetooth
    await FlutterBluetoothSerial.instance.requestEnable();
    }
    
    Future<void> _connectToBluetooth() async {
    String address = 'your_hc05_mac_address';
    try {
      _connection = await BluetoothConnection.toAddress(address);
      print('Connected to the device');
      _connection.input!.listen((Uint8List data) {
        setState(() {
          _dataBuffer.addAll(data);
          print('Received data: ${String.fromCharCodes(data)}');
        });
      });
    } catch (ex) {
      print('Error connecting to Bluetooth: $ex');
    }
    }
    
    @override
    Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Bluetooth Communication'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: _connectToBluetooth,
          child: Text('Connect to Bluetooth'),
        ),
      ),
    );
    }
    
    @override
    void dispose() {
    _connection.close();
    super.dispose();
    }
    }
    
    Login or Signup to reply.
  2. I guess you have to try few things.

    1. Check if the VCC of HC-05 is connected to 5V rather than 3.3V (It worked for me)
    2. Check if Bluetooth is turned on in your device. Try using a physical device.
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search