java rxtx下载_1、下载64位rxtx for java 链接:http://fizzed.com/oss/rxtx-for-java2、下载下来的包解压后按照说明放到JAV...

1、下载64位rxtx for java 链接:http://fizzed.com/oss/rxtx-for-java

2、下载下来的包解压后按照说明放到JAVA_HOME即JAVA的安装路径下面去

3、在maven的pom.xml下添加

org.rxtx

rxtx

2.1.7

4、串口API

CommPort:端口的抽象类

CommPortIdentifier:对串口访问和控制的核心类

SerialPort:通过它可以直接对串口进行读、写及设置工作

5、列出本机可用端口

Enumeration em = CommPortIdentifier.getPortIdentifiers();

while (em.hasMoreElements()) {

String name = em.nextElement().getName();

System.out.println(name);

}

6、一般步骤:打开串口得到串口对象==》设置参数==》对串口进行读写==》关闭串口,其中对串口进行读操作比较常用

//打开串口

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(); //关闭串口

Abc类内容,即读串口的具体操作:

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();

总结

以上就是本文关于java 串口通信实现流程示例的全部内容,希望对大家有所帮助。如有问题可以随时留言,期待您的宝贵意见。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值