我正在为我的移动应用程序使用 flutter。我想使用 HC-05 模块将我的移动应用程序与 Arduino 连接。
我的flutter代码(大代码中的一小段代码):
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('\n\nConnecting 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("\n\nReceiving 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();
...
}
}
我的arduino代码:
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);
}
当我运行我的 flutter 代码时,它会询问位置(以扫描可用的蓝牙设备)。
当我为 arduino 和 HC-05(红色和蓝色)供电时,我的 HC-05 模块会像往常一样闪烁。然后2/3秒后,蓝光消失。然后过了一会儿,两个灯都亮了(不闪烁)。
我的 flutter 代码返回错误:
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
请帮助我找出发生此错误的原因以及消除该错误的方法。
试试这个
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();
}
}