如何在Flutter中连接到Arduino的HC-05?

kd3sttzy  于 2023-11-21  发布在  Flutter
关注(0)|答案(1)|浏览(108)
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应用程序未连接到模块。

1wnzp6jl

1wnzp6jl1#

你可以试试这个:

connection = await BluetoothConnection.toAddress("MAC Address HC-05"); //Use your MAC address here

字符串

相关问题