Integrating Flutter with Arduino for Hardware Communication

Created At: 2024-06-30 13:36:24 Updated At: 2024-06-30 13:40:04

This guide demonstrates how to integrate Flutter with Arduino to enable communication with hardware peripherals using Bluetooth and USB serial communication. The Bluetooth method utilizes the flutter_blue package, while the USB method leverages the flutter_usb_serial package. Both approaches include detailed Arduino and Flutter code examples, allowing developers to read sensor data from Arduino and display it in a Flutter application. This integration facilitates the creation of interactive and responsive applications that can communicate directly with hardware components.

Method 1: Using Bluetooth

  1. Arduino Setup:

    • Connect a Bluetooth module (e.g., HC-05) to Arduino.
    • Write code to read sensor data and send it via Bluetooth.
  2. Flutter Setup:

    • Add the flutter_blue package to your Flutter project.
    • Use the package to scan for Bluetooth devices, connect to the Arduino, and receive data.

Method 2: Using USB Serial Communication

  1. Arduino Setup:

    • Write code to read sensor data and send it via Serial (USB).
  2. Flutter Setup:

    • For Android, add the flutter_usb_serial package.
    • Use the package to connect to the Arduino via USB and receive data.

Arduino Code (Bluetooth)

#include

SoftwareSerial BTSerial(10, 11); // RX, TX

 

void setup() {

  Serial.begin(9600);

  BTSerial.begin(9600);

}

void loop() {

  BTSerial.println("Hello from Arduino");

  delay(1000);

}

Flutter Code (Bluetooth)

import 'package:flutter/material.dart';

import 'package:flutter_blue/flutter_blue.dart'; 

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {

  @override

  Widget build(BuildContext context) {

    return MaterialApp(

      home: BluetoothPage(),

    );

  }

}

 

class BluetoothPage extends StatefulWidget {

  @override

  _BluetoothPageState createState() => _BluetoothPageState();

}

 

class _BluetoothPageState extends State {

  FlutterBlue flutterBlue = FlutterBlue.instance;

  BluetoothDevice? connectedDevice;

  BluetoothCharacteristic? characteristic;

 

  @override

  void initState() {

    super.initState();

    scanForDevices();

  }

 

  void scanForDevices() {

    flutterBlue.startScan(timeout: Duration(seconds: 4));

 

    var subscription = flutterBlue.scanResults.listen((results) {

      for (ScanResult r in results) {

        if (r.device.name == "YourDeviceName") {

          flutterBlue.stopScan();

          connectToDevice(r.device);

          break;

        }

      }

    });

  }

 

  void connectToDevice(BluetoothDevice device) async {

    await device.connect();

    setState(() {

      connectedDevice = device;

    });

    discoverServices();

  }

 

  void discoverServices() async {

    if (connectedDevice == null) return;

    List services = await connectedDevice!.discoverServices();

    for (var service in services) {

      for (var c in service.characteristics) {

        if (c.properties.notify) {

          characteristic = c;

          await c.setNotifyValue(true);

          c.value.listen((value) {

            // handle data received from Arduino

            print(value);

          });

        }

      }

    }

  }

 

  @override

  Widget build(BuildContext context) {

    return Scaffold(

      appBar: AppBar(title: Text('Flutter Bluetooth')),

      body: Center(

        child: Text('Connected to ${connectedDevice?.name ?? 'None'}'),

      ),

    );

  }

}

Arduino Code (USB)

void setup() {

  Serial.begin(9600);

}

 

void loop() {

  Serial.println("Hello from Arduino");

  delay(1000);

}

Flutter Code (USB)

import 'package:flutter/material.dart';

import 'package:flutter_usb_serial/flutter_usb_serial.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {

  @override

  Widget build(BuildContext context) {

    return MaterialApp(

      home: USBPage(),

    );

  }

}

 

class USBPage extends StatefulWidget {

  @override

  _USBPageState createState() => _USBPageState();

}

 

class _USBPageState extends State {

  UsbPort? usbPort;

 

  @override

  void initState() {

    super.initState();

    connectToUSB();

  }

 

  void connectToUSB() async {

    List devices = await UsbSerial.listDevices();

    if (devices.isNotEmpty) {

      UsbPort port = (await devices[0].create())!;

      await port.open();

      await port.setDTR(true);

      await port.setRTS(true);

      await port.setPortParameters(9600, UsbPort.DATABITS_8, UsbPort.STOPBITS_1, UsbPort.PARITY_NONE);

      port.inputStream?.listen((Uint8List event) {

        // handle data received from Arduino

        print(event);

      });

      setState(() {

        usbPort = port;

      });

    }

  }

 

  @override

  Widget build(BuildContext context) {

    return Scaffold(

      appBar: AppBar(title: Text('Flutter USB')),

      body: Center(

        child: Text('Connected to ${usbPort != null ? 'USB Device' : 'None'}'),

      ),

    );

  }

}

Summary

  • Bluetooth Method: Use flutter_blue for Bluetooth communication between Flutter and Arduino.
  • USB Method: Use flutter_usb_serial for USB serial communication between Flutter and Arduino.

These examples should help you integrate Flutter with Arduino for hardware interactions.

Comment

Add Reviews