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"),
),
),
);
}
}
字符串
我无法使用此代码连接到HC-05。谁能指出其中的错误或为我提供另一种连接到模块的方法?
我想从HC-05接收文本,但我的Flutter应用程序未连接到模块。
1条答案
按热度按时间1wnzp6jl1#
你可以试试这个:
字符串