flutter - Bluetooth scans but doesn't find hc-05 - Stack Overflow

admin2025-05-02  1

Bluetooth is scanning but it doesn't find the hc-05 what is the reason?

\`

import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import'premission.dart';

import 'package:flutter/material.dart';

import 'package:permission_handler/permission_handler.dart';

String weathercon1 = "غبار";
String weathercon2 = "8:00 PM";
List\<String\> weathercon = \["غبار", "لا غبار"\];
int currentValue = 0;

List\<String\> firstImage = \[
"assets/images/sandstorm.png",
"assets/images/no-removebg-preview.png"
\];
List\<String\> secondImage = \[
"assets/images/sundist.png",
"assets/images/Untitled-removebg-preview.png"
\];
List\<String\> thirdImage = \[
"assets/images/storm.png",
"assets/images/no-removebg-preview.png"
\];
String curImage = firstImage\[0\];
String curImage1 = secondImage\[0\];
String curImage2 = thirdImage\[0\];
String curWeather = weathercon\[0\];

void main() async{
WidgetsFlutterBinding.ensureInitialized();

bool bluetoothGranted = await requestBluetoothAccess();
if (bluetoothGranted) {
print("Bluetooth permissions granted!");
} else {
print("Bluetooth permissions denied!");
}
runApp(const MainApp());
}

class MainApp extends StatefulWidget {
const MainApp({super.key});

@override
State\<MainApp\> createState() =\> \_MainAppState();
}

class \_MainAppState extends State\<MainApp\> {
final FlutterBluePlus \_flutterBlue = FlutterBluePlus();
BluetoothDevice? \_connectedDevice;
bool \_isScanning = false;
bool \_isConnected = false;
String \_status = 'Disconnected';
BluetoothDevice? \_deviceToConnect;

@override
void initState() {
super.initState();
\_requestPermissions(); // طلب الأذونات عند بدء التطبيق
}

// طلب الأذونات اللازمة
void \_requestPermissions() async {
var status = await Permission.bluetoothScan.status;
if (!status.isGranted) {
await Permission.bluetoothScan.request();
}

    var statusConnect = await Permission.bluetoothConnect.status;
    if (!statusConnect.isGranted) {
      await Permission.bluetoothConnect.request();
    }

}

// بدء المسح عن الأجهزة
void \_startScan() async {
setState(() {
\_isScanning = true;
});

    FlutterBluePlus.startScan(timeout: Duration(seconds:10));
    
    FlutterBluePlus.scanResults.listen((results) {
      for (ScanResult result in results) {
        print('Found device: ${result.device.name}');
        if (result.device.name == 'HC-05') {  // إذا تم العثور على جهاز HC-05
          setState(() {
            _deviceToConnect = result.device;  // تعيين الجهاز الذي تم العثور عليه
          });
          _connectToDevice(result.device);  // الاتصال بالجهاز
          break;
        }
      }
    });
    
    FlutterBluePlus.isScanning.listen((isScanning) {
      setState(() {
        _isScanning = isScanning;
      });
    });

}

// الاتصال بالجهاز
void \_connectToDevice(BluetoothDevice device) async {
try {
await device.connect();
setState(() {
\_connectedDevice = device;
\_isConnected = true;
\_status = 'Connected';
});
print('Connected to ${device.name}');
} catch (e) {
setState(() {
\_status = 'Error connecting to device';
});
print('Error connecting to device: $e');
}
}

// فصل الاتصال بالجهاز
void \_disconnectDevice() async {
if (\_connectedDevice != null) {
await \_connectedDevice!.disconnect();
setState(() {
\_isConnected = false;
\_status = 'Disconnected';
});
print('Disconnected from ${\_connectedDevice?.name}');
}
}
@override
void dispose() {
FlutterBluePlus.stopScan(); // إيقاف المسح عند الخروج من الصفحة
super.dispose();
}

int curImageIndex = 0;
int curImageIndex1 = 0;
int curImageIndex2 = 0;
int curWeatherIndex = 0;

// التبديل بين الصور والحالة
void toggleImage() {
setState(() {
curImageIndex = (curImageIndex + 1) % firstImage.length;
curImage = firstImage\[curImageIndex\];

      curImageIndex1 = (curImageIndex1 + 1) % secondImage.length;
      curImage1 = secondImage[curImageIndex1];
    
      curImageIndex2 = (curImageIndex2 + 1) % thirdImage.length;
      curImage2 = thirdImage[curImageIndex2];
    
      curWeatherIndex = (curWeatherIndex + 1) % weathercon.length;
      curWeather = weathercon[curWeatherIndex];
    });

}

@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
appBar: AppBar(
toolbarHeight: 20,
backgroundColor: Colors.white,
),
backgroundColor: Colors.white,
body: SingleChildScrollView(
child: Column(
children: \[
Stack(
children: \[
Row(
children: \[
SizedBox(
height: 218,
child: Image.asset("assets/images/weather.png"),
),
\],
),
Positioned(
top: 0,
right: 0,
child: Image.asset(
"assets/images/string.png",
width: 200,
),
),
\],
),
Container(
height: 90,
width: 300,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
color: const Color.fromARGB(255, 211, 198, 164),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: \[
const Padding(
padding: EdgeInsets.all(10.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.end,
children: \[
Text("صباح الخير", style: TextStyle(fontSize: 17)),
Text(
"موقعك الحالي",
style: TextStyle(
fontWeight: FontWeight.bold, fontSize: 20),
),
\],
),
),
Container(
height: 90,
width: 100,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
gradient: const LinearGradient(
begin: Alignment.bottomCenter,
end: Alignment.topCenter,
colors: \[
Color.fromARGB(255, 61, 132, 152),
Colors.white,
\],
),
),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: \[
SizedBox(
height: 50,
width: 50,
child: GestureDetector(
onTap: () {
toggleImage();
},
child:
Image.asset(curImage, height: 20, width: 20),
),
),
Text(
curWeather,
style: const TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 11,
),
),
Text(
weathercon2,
style: const TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 11),
),
\],
),
),
\],
),
),
SizedBox(height: 100, width: 500, child: Image.asset(curImage1)),
Container(
height: 140,
width: 353,
decoration: const BoxDecoration(
color: Color.fromARGB(255, 211, 198, 164),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: \[
Column(
children: \[
const Text("حالة الطقس اليوم"),
const Text("الطقس المتوقع في الساعات القادمة"),
const Text(".....توقعات الطقس لمدة عشر أيام"),
Row(
children: \[
SizedBox(
height: 60,
width: 75,
child: Image.asset(curImage2),
),
\],
),
\],
),
Container(color: Colors.black, height: 120, width: 3),
Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: \[
Image.asset(
"assets/images/logo-removebg-preview.png",
width: 90,
height: 90,
),
const Text(
"الطقس",
style: TextStyle(
fontWeight: FontWeight.bold, fontSize: 15),
),
const Text(
"اليوم",
style: TextStyle(
fontWeight: FontWeight.bold, fontSize: 15),
),
\],
),
\],
),
),
Align(
alignment: Alignment.bottomLeft,
child: Row(
children: \[
Container(
margin: const EdgeInsets.all(10),
decoration: BoxDecoration(
border: Border.all(color: Colors.black, width: 2),
borderRadius: BorderRadius.circular(50),
),
child:Column(
children: \[
ElevatedButton(
onPressed: \_isScanning ? null : \_startScan,  // بدء المسح
child: Text(\_isScanning ? 'Scanning...' : 'Start Scanning'),
),
ElevatedButton(
onPressed: \_isConnected ? \_disconnectDevice : null, // فصل الاتصال
child: Text('Disconnect'),
),
Text(
'Status: $\_status', // حالة الاتصال
style: TextStyle(fontSize: 20),
),
if (\_connectedDevice != null)
Text(
'Connected to: ${\_connectedDevice?.name}',
style: TextStyle(fontSize: 16),
),
\],
),

                    ),
    
    
    
                  ],
                ),
              ),
              Column(
                children: [
                  Image.asset(
                    'assets/images/Picture1.png',
                    width: 100,
                    height: 100,
                  ),
                  const Text("مدرسة أم كلثوم بنت عقبة المتوسطة بنات")
                ],
              ),
            ],
          ),
        ),
      ),
    );

}
}\`

I tried to increase the scan but it didn't work and I added many permissions but they didn't charge either. I tried all sorts of ways to solve it but nothing worked.I neeeeeeed help ..................................................................................................................................................................................................................................................................

Bluetooth is scanning but it doesn't find the hc-05 what is the reason?

\`

import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import'premission.dart';

import 'package:flutter/material.dart';

import 'package:permission_handler/permission_handler.dart';

String weathercon1 = "غبار";
String weathercon2 = "8:00 PM";
List\<String\> weathercon = \["غبار", "لا غبار"\];
int currentValue = 0;

List\<String\> firstImage = \[
"assets/images/sandstorm.png",
"assets/images/no-removebg-preview.png"
\];
List\<String\> secondImage = \[
"assets/images/sundist.png",
"assets/images/Untitled-removebg-preview.png"
\];
List\<String\> thirdImage = \[
"assets/images/storm.png",
"assets/images/no-removebg-preview.png"
\];
String curImage = firstImage\[0\];
String curImage1 = secondImage\[0\];
String curImage2 = thirdImage\[0\];
String curWeather = weathercon\[0\];

void main() async{
WidgetsFlutterBinding.ensureInitialized();

bool bluetoothGranted = await requestBluetoothAccess();
if (bluetoothGranted) {
print("Bluetooth permissions granted!");
} else {
print("Bluetooth permissions denied!");
}
runApp(const MainApp());
}

class MainApp extends StatefulWidget {
const MainApp({super.key});

@override
State\<MainApp\> createState() =\> \_MainAppState();
}

class \_MainAppState extends State\<MainApp\> {
final FlutterBluePlus \_flutterBlue = FlutterBluePlus();
BluetoothDevice? \_connectedDevice;
bool \_isScanning = false;
bool \_isConnected = false;
String \_status = 'Disconnected';
BluetoothDevice? \_deviceToConnect;

@override
void initState() {
super.initState();
\_requestPermissions(); // طلب الأذونات عند بدء التطبيق
}

// طلب الأذونات اللازمة
void \_requestPermissions() async {
var status = await Permission.bluetoothScan.status;
if (!status.isGranted) {
await Permission.bluetoothScan.request();
}

    var statusConnect = await Permission.bluetoothConnect.status;
    if (!statusConnect.isGranted) {
      await Permission.bluetoothConnect.request();
    }

}

// بدء المسح عن الأجهزة
void \_startScan() async {
setState(() {
\_isScanning = true;
});

    FlutterBluePlus.startScan(timeout: Duration(seconds:10));
    
    FlutterBluePlus.scanResults.listen((results) {
      for (ScanResult result in results) {
        print('Found device: ${result.device.name}');
        if (result.device.name == 'HC-05') {  // إذا تم العثور على جهاز HC-05
          setState(() {
            _deviceToConnect = result.device;  // تعيين الجهاز الذي تم العثور عليه
          });
          _connectToDevice(result.device);  // الاتصال بالجهاز
          break;
        }
      }
    });
    
    FlutterBluePlus.isScanning.listen((isScanning) {
      setState(() {
        _isScanning = isScanning;
      });
    });

}

// الاتصال بالجهاز
void \_connectToDevice(BluetoothDevice device) async {
try {
await device.connect();
setState(() {
\_connectedDevice = device;
\_isConnected = true;
\_status = 'Connected';
});
print('Connected to ${device.name}');
} catch (e) {
setState(() {
\_status = 'Error connecting to device';
});
print('Error connecting to device: $e');
}
}

// فصل الاتصال بالجهاز
void \_disconnectDevice() async {
if (\_connectedDevice != null) {
await \_connectedDevice!.disconnect();
setState(() {
\_isConnected = false;
\_status = 'Disconnected';
});
print('Disconnected from ${\_connectedDevice?.name}');
}
}
@override
void dispose() {
FlutterBluePlus.stopScan(); // إيقاف المسح عند الخروج من الصفحة
super.dispose();
}

int curImageIndex = 0;
int curImageIndex1 = 0;
int curImageIndex2 = 0;
int curWeatherIndex = 0;

// التبديل بين الصور والحالة
void toggleImage() {
setState(() {
curImageIndex = (curImageIndex + 1) % firstImage.length;
curImage = firstImage\[curImageIndex\];

      curImageIndex1 = (curImageIndex1 + 1) % secondImage.length;
      curImage1 = secondImage[curImageIndex1];
    
      curImageIndex2 = (curImageIndex2 + 1) % thirdImage.length;
      curImage2 = thirdImage[curImageIndex2];
    
      curWeatherIndex = (curWeatherIndex + 1) % weathercon.length;
      curWeather = weathercon[curWeatherIndex];
    });

}

@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
appBar: AppBar(
toolbarHeight: 20,
backgroundColor: Colors.white,
),
backgroundColor: Colors.white,
body: SingleChildScrollView(
child: Column(
children: \[
Stack(
children: \[
Row(
children: \[
SizedBox(
height: 218,
child: Image.asset("assets/images/weather.png"),
),
\],
),
Positioned(
top: 0,
right: 0,
child: Image.asset(
"assets/images/string.png",
width: 200,
),
),
\],
),
Container(
height: 90,
width: 300,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
color: const Color.fromARGB(255, 211, 198, 164),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: \[
const Padding(
padding: EdgeInsets.all(10.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.end,
children: \[
Text("صباح الخير", style: TextStyle(fontSize: 17)),
Text(
"موقعك الحالي",
style: TextStyle(
fontWeight: FontWeight.bold, fontSize: 20),
),
\],
),
),
Container(
height: 90,
width: 100,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
gradient: const LinearGradient(
begin: Alignment.bottomCenter,
end: Alignment.topCenter,
colors: \[
Color.fromARGB(255, 61, 132, 152),
Colors.white,
\],
),
),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: \[
SizedBox(
height: 50,
width: 50,
child: GestureDetector(
onTap: () {
toggleImage();
},
child:
Image.asset(curImage, height: 20, width: 20),
),
),
Text(
curWeather,
style: const TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 11,
),
),
Text(
weathercon2,
style: const TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 11),
),
\],
),
),
\],
),
),
SizedBox(height: 100, width: 500, child: Image.asset(curImage1)),
Container(
height: 140,
width: 353,
decoration: const BoxDecoration(
color: Color.fromARGB(255, 211, 198, 164),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: \[
Column(
children: \[
const Text("حالة الطقس اليوم"),
const Text("الطقس المتوقع في الساعات القادمة"),
const Text(".....توقعات الطقس لمدة عشر أيام"),
Row(
children: \[
SizedBox(
height: 60,
width: 75,
child: Image.asset(curImage2),
),
\],
),
\],
),
Container(color: Colors.black, height: 120, width: 3),
Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: \[
Image.asset(
"assets/images/logo-removebg-preview.png",
width: 90,
height: 90,
),
const Text(
"الطقس",
style: TextStyle(
fontWeight: FontWeight.bold, fontSize: 15),
),
const Text(
"اليوم",
style: TextStyle(
fontWeight: FontWeight.bold, fontSize: 15),
),
\],
),
\],
),
),
Align(
alignment: Alignment.bottomLeft,
child: Row(
children: \[
Container(
margin: const EdgeInsets.all(10),
decoration: BoxDecoration(
border: Border.all(color: Colors.black, width: 2),
borderRadius: BorderRadius.circular(50),
),
child:Column(
children: \[
ElevatedButton(
onPressed: \_isScanning ? null : \_startScan,  // بدء المسح
child: Text(\_isScanning ? 'Scanning...' : 'Start Scanning'),
),
ElevatedButton(
onPressed: \_isConnected ? \_disconnectDevice : null, // فصل الاتصال
child: Text('Disconnect'),
),
Text(
'Status: $\_status', // حالة الاتصال
style: TextStyle(fontSize: 20),
),
if (\_connectedDevice != null)
Text(
'Connected to: ${\_connectedDevice?.name}',
style: TextStyle(fontSize: 16),
),
\],
),

                    ),
    
    
    
                  ],
                ),
              ),
              Column(
                children: [
                  Image.asset(
                    'assets/images/Picture1.png',
                    width: 100,
                    height: 100,
                  ),
                  const Text("مدرسة أم كلثوم بنت عقبة المتوسطة بنات")
                ],
              ),
            ],
          ),
        ),
      ),
    );

}
}\`

I tried to increase the scan but it didn't work and I added many permissions but they didn't charge either. I tried all sorts of ways to solve it but nothing worked.I neeeeeeed help ..................................................................................................................................................................................................................................................................

Share Improve this question asked Jan 2 at 12:03 somaya mohamadsomaya mohamad 211 bronze badge 1
  • question has too much code (and needs to be formatted properly) – Kop3sh Commented Jan 2 at 14:32
Add a comment  | 

1 Answer 1

Reset to default 1

Although the HC-05 Bluetooth module uses 'Bluetooth classic' technology, you are trying to discover the module using 'Bluetooth LE' technology, which is incompatible.

You should probably use a library such as bluetooth_classic or flutter_blue_classic

转载请注明原文地址:http://anycun.com/QandA/1746121840a91973.html