티스토리 뷰

esp32 드론 만들기

모터 테스트를 위해 플러터앱으로 드론으로 숫자를 보내면 모터가 회전하도록 앱을 만들었다

완성된 앱은 아니고 테스트용 앱이다

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

void main() {
  runApp(MySimpleApp());
}

class MySimpleApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Drone Controller App',
      home: BluetoothApp(),
    );
  }
}

class BluetoothApp extends StatefulWidget {
  @override
  _BluetoothAppState createState() => _BluetoothAppState();
}

class _BluetoothAppState extends State<BluetoothApp> {
  List<BluetoothDevice> _devicesList = [];
  BluetoothConnection? _connection;
  bool _isConnected = false;
  final TextEditingController _textController = TextEditingController();

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

  void _getDevices() async {
    List<BluetoothDevice> devices = await FlutterBluetoothSerial.instance.getBondedDevices();
    setState(() {
      _devicesList = devices;
    });
  }

  void _connect(BluetoothDevice device) async {
    try {
      BluetoothConnection connection = await BluetoothConnection.toAddress(device.address);
      setState(() {
        _connection = connection;
        _isConnected = true;
      });
    } catch (e) {
      setState(() {
        _isConnected = false;
      });
      showDialog(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            title: Text("Error"),
            content: Text("Cannot connect to device"),
            actions: [
              TextButton(
                child: Text("OK"),
                onPressed: () {
                  Navigator.of(context).pop();
                },
              ),
            ],
          );
        },
      );
    }
  }

  void _sendData() async {
    if (_connection != null && _isConnected) {
      _connection!.output.add(utf8.encode(_textController.text)); // Send the text to the Bluetooth device
      await _connection!.output.allSent;
      setState(() {
        _textController.text = ''; // Optionally clear the text field after sending
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Drone Controller'),
      ),
      body: Column(
        children: <Widget>[
          ElevatedButton(
            onPressed: _getDevices,
            child: Text('Scan for Devices'),
          ),
          Expanded(
            child: ListView.builder(
              itemCount: _devicesList.length,
              itemBuilder: (context, index) {
                return ListTile(
                  title: Text(_devicesList[index].name ?? "Unknown Device"),
                  subtitle: Text(_devicesList[index].address),
                  trailing: ElevatedButton(
                    onPressed: () => _connect(_devicesList[index]),
                    child: Text(_isConnected ? 'Disconnect' : 'Connect'),
                  ),
                );
              },
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: TextField(
              controller: _textController,
              decoration: InputDecoration(
                border: OutlineInputBorder(),
                labelText: 'Enter number to send',
              ),
              keyboardType: TextInputType.number,
            ),
          ),
          ElevatedButton(
            onPressed: _sendData,
            child: Text('Send'),
          ),
        ],
      ),
    );
  }
}

드론 연결하고 모터 속도 테스트는 가능한 걸로 확인이 되었다

다만 1과 2를 보내면 모터가 돌아가는데

3을 보내면 배터리가 없어서인지 모터가 멈춰버린다

배터리 충전기가 어디에 있는지 찾아봐야겠다