embedded_serialport 1.5.4 embedded_serialport: ^1.5.4 copied to clipboard
`embedded_serialport` is a Flutter package for serial port communication, using Dart FFI to interact with Rust and C libraries. It lists serial ports and handles read/write operations.
import 'package:flutter/material.dart';
import 'package:embedded_serialport/embedded_serialport.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Serial Port Example',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const SerialPortPage(),
);
}
}
class SerialPortPage extends StatefulWidget {
const SerialPortPage({super.key});
@override
// ignore: library_private_types_in_public_api
_SerialPortPageState createState() => _SerialPortPageState();
}
class _SerialPortPageState extends State<SerialPortPage> {
late Serial _serial;
List<String> _ports = [];
String _output = "";
@override
void initState() {
super.initState();
_initializeSerialPort();
}
void _initializeSerialPort() {
_ports = Serial.getPorts();
if (_ports.isNotEmpty) {
_serial = Serial(_ports.first, Baudrate.b115200);
_serial.timeout(2);
}
setState(() {});
}
void _writeString(String command) {
_serial.writeString(command);
var event = _serial.read(20);
setState(() {
_output += "$command -> ${event.toString()}\n";
});
}
void _disposeSerialPort() {
_serial.dispose();
}
@override
void dispose() {
_disposeSerialPort();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Serial Port Example'),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
children: [
Text('Available Ports: ${_ports.join(", ")}'),
const SizedBox(height: 20),
ElevatedButton(
onPressed: () => _writeString('led,0'),
child: const Text('Send "led,0"'),
),
ElevatedButton(
onPressed: () => _writeString('led'),
child: const Text('Send "led"'),
),
const SizedBox(height: 20),
Expanded(
child: SingleChildScrollView(
child: Text(_output),
),
),
],
),
),
);
}
}