一个 Flutter 插件,可在 Windows 上使用原生 win32 API 实现串口通信。它允许通过串口直接连接物理设备,例如微控制器、传感器或工业设备。专为 Windows 设计,提供低级别访问且抽象程度极低,适合需要在桌面应用程序中实现可靠高效串口通信的开发者。该包可与 Flutter 生态系统无缝集成,非常适合硬件相关项目。
适合场景
连接到Arduino或类似的微控制器
从工业传感器读取数据
通过串行协议控制硬件设备
为嵌入式系统开发桌面应用程序
与串行外设建立实时通信
主要特点
原生 win32 API 集成
仅限 Windows 的平台支持
低延迟串行通信
用于打开/关闭端口的简单 API
支持波特率和校验位配置
实时数据流
适合对象
Windows 桌面应用程序开发者
硬件接口项目
物联网设备控制应用
嵌入式系统集成
实时数据采集工具
使用建议
仅限 Windows 操作系统
某些操作需要管理员权限
不支持 Linux 或 macOS
需要手动处理错误
依赖于特定于 Windows 的系统调用
原始 README
以下为关联源码仓库的 README 原文快照,最新内容请访问源码仓库。
serial_port_win32
A SerialPort library using win32 API.
Breaking Changes from 2.x.x to 3.x.x
Due to many major changes in win32 package, this package need to break some APIs.
Some main APIs change below:
set Parity(int parity) -> set Parity(DCB_PARITY parity)
set StopBits(int stopBits) -> set StopBits(DCB_STOP_BITS stopBits)
final LPWSTR _portNameUtf16; -> final PCWSTR _portNameUtf16;
Some Exceptions change to WindowsExceptions
Deprecated
@Deprecated("Use win32 constant CLRDTR instead of this, because it is more clear to understand")
staticconstint CLRDTR = 6;
/// Clears the RTS (request-to-send) signal.@Deprecated("Use win32 constant CLRRTS instead of this, because it is more clear to understand")
staticconstint CLRRTS = 4;
/// Sends the DTR (data-terminal-ready) signal.@Deprecated("Use win32 constant SETDTR instead of this, because it is more clear to understand")
staticconstint SETDTR = 5;
/// Sends the RTS (request-to-send) signal.@Deprecated("Use win32 constant SETRTS instead of this, because it is more clear to understand")
staticconstint SETRTS = 3;
Getting Started
Get Ports
final ports = SerialPort.getAvailablePorts();
print(ports);
/// result like [COM3, COM4]
The port instance is Singleton Pattern. Don't re-create port for same Com name.
final port = SerialPort("COM5", openNow: true, ByteSize: 8, BaudRate: 9600);
// orfinal port = SerialPort("COM5", openNow: false, ByteSize: 8, BaudRate: 9600);
port.open();
// or
port.openWithSettings(BaudRate: CBR_115200);
// final port = SerialPort("COM5"); /// auto open with default settings
Read
There are several methods to read bytes from serial port.
readBytesUntil
[readBytesUntil] will read until an [expected] sequence is found
readBytes
General Read with the timeout parameter.
readFixedSizeBytes
[readFixedSizeBytes] will always read until readData.length == bytesSize.
print(await port.readBytesUntil(Uint8List.fromList("T".codeUnits))); /// '\0' is not included/// orvar read = port.readBytes(18, timeout: Duration(milliseconds: 10))..then((onValue) => print(onValue));
var result = await read;
print(result);
/// orvar fixedBytesRead = port.readFixedSizeBytes(2)..then((onValue) => print(onValue));
await fixedBytesRead;
/// see more in small example