You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter无法连接Arduino的HC-05模块,求排查与解决方案

问题分析与修正方案

代码中的核心错误

  • 扫描方法调用语法错误:flutterBluetoothSerial.() 应为 flutterBluetoothSerial.startDiscovery()
  • 连接逻辑错误:BluetoothDevice 本身无 connect()、write()、read() 方法,需通过 BluetoothConnection.toAddress() 建立连接后,用连接对象处理读写操作
  • 未处理扫描重复触发:找到HC-05后未停止扫描,会多次尝试连接
  • 缺少权限与蓝牙状态检查:未确认蓝牙是否开启、是否获取必要权限
  • 无异常处理:连接、读写过程未捕获错误,易导致应用崩溃

修正后的完整代码

import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter_bluetooth_serial/flutter_bluetooth_serial.dart';

void main() {
  runApp(const MyApp());
}

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

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final FlutterBluetoothSerial _bluetooth = FlutterBluetoothSerial.instance;
  BluetoothDevice? _hc05Device;
  BluetoothConnection? _connection;
  bool _isConnected = false;
  String _receivedData = "";

  @override
  void initState() {
    super.initState();
    _initBluetooth();
  }

  Future<void> _initBluetooth() async {
    // 检查蓝牙是否开启,未开启则请求开启
    bool isEnabled = await _bluetooth.isEnabled;
    if (!isEnabled) {
      await _bluetooth.requestEnable();
    }

    // 请求蓝牙相关权限
    await _bluetooth.requestPermissions();

    // 启动设备扫描
    _startDeviceScan();
  }

  void _startDeviceScan() {
    _bluetooth.startDiscovery().listen((result) {
      if (result.device.name == "HC-05" && _hc05Device == null) {
        setState(() {
          _hc05Device = result.device;
        });
        _bluetooth.cancelDiscovery(); // 找到目标设备后停止扫描
        _connectToDevice();
      }
    });
  }

  Future<void> _connectToDevice() async {
    if (_hc05Device == null) return;

    try {
      _connection = await BluetoothConnection.toAddress(_hc05Device!.address);
      setState(() {
        _isConnected = true;
      });
      print("已连接到HC-05");

      // 持续监听HC-05发送的数据
      _connection!.input!.listen((data) {
        String received = String.fromCharCodes(data);
        setState(() {
          _receivedData += received;
        });
        print("收到数据: $received");
      }).onDone(() {
        setState(() {
          _isConnected = false;
        });
        print("连接已断开");
      });

      // 向HC-05发送测试数据
      _sendData("Hello from Flutter!");
    } catch (e) {
      print("连接失败: $e");
      setState(() {
        _isConnected = false;
      });
    }
  }

  void _sendData(String message) {
    if (_connection != null && _isConnected) {
      _connection!.output.add(Uint8List.fromList(message.codeUnits));
      _connection!.output.allSent.then((_) {
        print("数据发送成功");
      });
    }
  }

  @override
  void dispose() {
    _connection?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text("HC-05 蓝牙连接"),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(_isConnected ? "已连接HC-05" : "未连接"),
              const SizedBox(height: 20),
              SizedBox(
                width: 250,
                child: Text("收到的数据:\n$_receivedData"),
              ),
              const SizedBox(height: 20),
              ElevatedButton(
                onPressed: _isConnected ? null : _startDeviceScan,
                child: const Text("重新扫描"),
              )
            ],
          ),
        ),
      ),
    );
  }
}

额外注意事项

  • HC-05配置:确保HC-05已与设备配对(默认密码多为1234或0000),Arduino端需通过Serial.println()等方法向蓝牙模块发送文本数据
  • Android权限配置:在AndroidManifest.xml中添加以下权限:
    <uses-permission android:name="android.permission.BLUETOOTH"/>
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <uses-permission android:name="android.permission.BLUETOOTH_CONNECT"/>
    <uses-permission android:name="android.permission.BLUETOOTH_SCAN"/>
    
  • iOS权限配置:在Info.plist中添加蓝牙权限描述:
    <key>NSBluetoothAlwaysUsageDescription</key>
    <string>需要蓝牙权限连接HC-05模块</string>
    <key>NSBluetoothPeripheralUsageDescription</key>
    <string>需要蓝牙权限连接HC-05模块</string>
    

内容的提问来源于stack exchange,提问作者droidworker

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 12:57:23