<dependency> <groupId>org.rxtx</groupId> <artifactId>rxtx</artifactId> <version>2.1.7</version> </dependency>
Enumeration<CommPortIdentifier> em = CommPortIdentifier.getPortIdentifiers();
while (em.hasMoreElements()) {
String name = em.nextElement().getName();
System.out.println(name);
}
//打开串口
CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier("COM4");//COM4是串口名字
CommPort commPort = portIdentifier.open("COM4", 2000); //2000是打开超时时间
serialPort = (SerialPort) commPort;
//设置参数(包括波特率,输入/输出流控制,数据位数,停止位和齐偶校验)
serialPort.setSerialPortParams(9600,
SerialPort.DATABITS_8, SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
//监听串口事件
serialPort.addEventListener(new Abc()); //Abc是实现SerialPortEventListener接口的类,具体读操作在里面进行
// 设置当有数据到达时唤醒监听接收线程
serialPort.notifyOnDataAvailable(true);
// 设置当通信中断时唤醒中断线程
serialPort.notifyOnBreakInterrupt(true);
// in.close(); //关闭串口
public class Abc implements SerialPortEventListener {
public void serialEvent(SerialPortEvent arg0) {
// TODO Auto-generated method stub
//对以下内容进行判断并操作
/*
BI -通讯中断
CD -载波检测
CTS -清除发送
DATA_AVAILABLE -有数据到达
DSR -数据设备准备好
FE -帧错误
OE -溢位错误
OUTPUT_BUFFER_EMPTY -输出缓冲区已清空
PE -奇偶校验错
RI - 振铃指示
*/
//switch多个,if单个
if (arg0.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
try {
InputStream in = null;
byte[] bytes = null;
in = App.serialPort.getInputStream();
int bufflenth = in.available();
while (bufflenth != 0) {
// 初始化byte数组为buffer中数据的长度
bytes = new byte[bufflenth];
in.read(bytes);
System.out.println(new String(bytes));
bufflenth = in.available();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
OutputStream out = serialPort.getOutputStream(); out.write(data); //byte[] data; out.flush();
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有