赞
踩
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();
}
}
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。