Reputation: 11
import 'package:flutter/material.dart';
import 'package:flutter_bluetooth_serial/flutter_bluetooth_serial.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
FlutterBluetoothSerial flutterBluetoothSerial =
FlutterBluetoothSerial.instance;
BluetoothDevice? device;
@override
void initState() {
super.initState();
// Start scanning for Bluetooth devices.
flutterBluetoothSerial.();
// Listen for scan results.
flutterBluetoothSerial.scanResults.listen((scanResults) {
for (var scanResult in scanResults) {
if (scanResult.device.name == "HC-05") {
device = scanResult.device;
connectToDevice();
}
}
});
}
void connectToDevice() async {
await device.connect();
print("Connected to HC-05");
// Send some data to the HC-05 module.
device.write("Hello, world!");
// Receive some data from the HC-05 module.
String data = await device.read();
print("Received data from HC-05: $data");
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text("Connect to HC-05"),
),
),
);
}
}
I am not able to connect to HC-05 using this code. Can anyone point out the mistake in this or provide me with another way to connect to my module?
I want to receive a text from HC-05 but my Flutter app is not connecting to the module.
Upvotes: 1
Views: 764
Reputation: 1
You can try this:
connection = await BluetoothConnection.toAddress("MAC Address HC-05"); //Use your MAC address here
Upvotes: 0