一、项目背景
在使用 姿态传感器(如 WitMotion 系列 YJ61、WT901 等) 时,我们通常会通过串口助手观察输出的 3D 姿态数据(帧头一般为 0x55)。
如果希望在 Java 程序 中读取这些数据并做进一步处理(比如姿态解算、3D 可视化),我们需要使用 Java 串口通信库。
这里我们选择 jSerialComm
库来实现串口数据读取,避免依赖厂商提供的 DLL。
二、开发环境
JDK 11
IDEA / Eclipse
依赖库:jSerialComm
Maven 引入方式:
<dependency>
<groupId>com.fazecast</groupId>
<artifactId>jSerialComm</artifactId>
<version>2.9.3</version>
</dependency>
三、串口参数配置
传感器串口参数(以 YJ61 为例):
- 端口号:COM7 (根据设备管理器调整)
- 波特率:115200
- 数据位:8
- 停止位:1
- 校验位:None
- 流控:无
在 Java 代码里需要完全一致,否则无法正确读取。
示例代码
提示:下面是一个极简 Java 示例,用来确认是否能成功读取传感器的原始字节流:
import com.fazecast.jSerialComm.SerialPort;
import java.io.InputStream;
public class SimpleSerialTest {
public static void main(String[] args) throws Exception {
SerialPort comPort = SerialPort.getCommPort("COM7");
comPort.setBaudRate(115200);
comPort.setNumDataBits(8);
comPort.setNumStopBits(1);
comPort.setParity(SerialPort.NO_PARITY);
comPort.setComPortTimeouts(SerialPort.TIMEOUT_READ_BLOCKING, 1000, 0);
if (!comPort.openPort()) {
System.out.println("串口打开失败");
return;
}
System.out.println("串口已连接,开始读取...");
// 读取数据
InputStream in = comPort.getInputStream();
while (true) {
int data = in.read();
if (data != -1) {
System.out.printf("%02X ", data);
}
}
}
}
运行效果
55 51 06 00 F8 FF 7A 01 ...
55 52 ...
55 53 ...
五、数据解析(以姿态角为例)
WitMotion 的数据帧格式一般如下:
- 帧头固定:0x55
- 功能码:0x51(加速度)、0x52(角速度)、0x53(角度)
- 数据长度:固定 9 字节(含校验)
例如角度帧 (0x53):
55 53 AxL AxH AyL AyH AzL AzH T
解析代码(只演示角度):
private static void parseFrame(byte[] buf) {
if (buf[0] == 0x55 && buf[1] == 0x53) {
int rollRaw = (buf[2] & 0xFF) | ((buf[3] & 0xFF) << 8);
int pitchRaw = (buf[4] & 0xFF) | ((buf[5] & 0xFF) << 8);
int yawRaw = (buf[6] & 0xFF) | ((buf[7] & 0xFF) << 8);
double roll = (rollRaw / 32768.0) * 180.0;
double pitch = (pitchRaw / 32768.0) * 180.0;
double yaw = (yawRaw / 32768.0) * 180.0;
System.out.printf("Roll=%.2f, Pitch=%.2f, Yaw=%.2f%n", roll, pitch, yaw);
}
}
六、后续
目前主要实现了在 Java + jSerialComm 环境下读取姿态传感器的串口数据,并完成了基础的角度解析,之后将完成传感器YJ61移动和静止的判断。

被折叠的 条评论
为什么被折叠?



