当前位置:   article > 正文

485串口 java_JAVA,串口,485信号,RXTX相关问题

java获取com口485

packagerxtx;importgnu.io.CommPort;importgnu.io.CommPortIdentifier;importgnu.io.SerialPort;importjava.io.FileDescriptor;importjava.io.IOException;importjava.io.InputStream;importjava.io.OutputStream;public classTwoWaySerialComm {publicTwoWaySerialComm() {super();

}void connect(String portName) throwsException {

CommPortIdentifier portIdentifier=CommPortIdentifier.getPortIdentifier(portName);if(portIdentifier.isCurrentlyOwned()) {

System.out.println("Error: Port is currently in use");

}else{//打开接口

CommPort commPort = portIdentifier.open(this.getClass().getName(), 2000);if (commPort instanceofSerialPort) {

SerialPort serialPort=(SerialPort) commPort;//设置串口通行控制:波特率=9600,数据位=8,停止位=1,无效验

serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1,

SerialPort.PARITY_NONE);//输入

InputStream in =serialPort.getInputStream();//输出

OutputStream out =serialPort.getOutputStream();

System.out.println("111");

(new Thread(newSerialReader(in))).start();

(new Thread(newSerialWriter(out))).start();

System.out.println("222");

}else{

System.out.println("Error: Only serial ports are handled by this example.");

}

}

}/**读取*/

public static class SerialReader implementsRunnable {

InputStream in;publicSerialReader(InputStream in) {this.in =in;

}public voidrun() {byte[] buffer = new byte[1024];int len = -1;try{while ((len = this.in.read(buffer)) > -1) {

System.out.print(new String(buffer, 0, len));

}

}catch(IOException e) {

e.printStackTrace();

}

}

}/**写出*/

public static class SerialWriter implementsRunnable {

OutputStream out;publicSerialWriter(OutputStream out) {this.out =out;

}public voidrun() {try{int c = 0;while ((c = System.in.read()) > -1) {this.out.write(c);

}

}catch(IOException e) {

e.printStackTrace();

}

}

}public static voidmain(String[] args) {try{

(new TwoWaySerialComm()).connect("COM3");

}catch(Exception e) {//TODO Auto-generated catch block

e.printStackTrace();

}

}

}

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/不正经/article/detail/289653
推荐阅读
相关标签
  

闽ICP备14008679号