Eclipse插件(Java)读写串口
前言
本例程主要借助CDT插件集中的Serial相关插件来实现串口的访问。CDT内部已经做了多平台的适配,一套代码可以在多种常见的平台上实现串口操作
target platform (依赖项或运行时)
<target name="my target">
<locations>
<location includeAllPlatforms="false" includeConfigurePhase="true" includeMode="planner" includeSource="true" type="InstallableUnit">
<repository location="https://download.eclipse.org/releases/2021-12/"/>
<unit id="org.eclipse.platform.sdk" version="0.0.0"/>
<unit id="org.eclipse.cdt.native.feature.group" version="0.0.0"/>
</location>
</locations>
</target>
主要API介绍
org.eclipse.cdt.serial.SerialPort 类
该类封装了访问串口的所有功能,一个SerialPort对象,代表一个串口
列出所有串口
String[] ports = SerialPort.list();
获取并初始化串口对象
String portName = "COM9";
SerialPort port = SerialPort.get(portName );
if (port == null) {
port = new SerialPort(portName );
}
if (port != null && !port.isOpen()) {
try {
port.setBaudRateValue(9600); // 设置波特率
port.open(); // 打开串口
} catch (IOException e) {
e.printStackTrace();
}
}
读串口
InputStream input = port.getInputStream();
byte[] buffer = new byte[128];
input.read(buffer); // 从串口的输入流读取数据
写串口
port.getOutputStream().write("Hello world!".getBytes()); // 向串口的输出流写数据