java rxtx 串口_java下的串口通信-RXTX

packagenir.desktop.demo;importgnu.io.CommPort;importgnu.io.CommPortIdentifier;importgnu.io.PortInUseException;importgnu.io.SerialPort;importgnu.io.SerialPortEvent;importgnu.io.SerialPortEventListener;importjava.io.IOException;importjava.io.InputStream;importjava.io.OutputStream;importjava.util.Enumeration;importjava.util.HashSet;public classSerialRXTX {/*** This code snippet shows how to retrieve the available comms ports on your

* computer. A CommPort is available if it is not being used by another

* application.*/

public static voidlistAvailablePorts() {

HashSet portSet =getAvailableSerialPorts();

String[] serialPort= newString[portSet.size()];int i = 0;for(CommPortIdentifier comm : portSet) {

serialPort[i]=comm.getName();

System.out.println(serialPort[i]);

i++;

}

}public static String getPortTypeName(intportType) {switch(portType) {caseCommPortIdentifier.PORT_I2C:return "I2C";caseCommPortIdentifier.PORT_PARALLEL:return "Parallel";caseCommPortIdentifier.PORT_RAW:return "Raw";caseCommPortIdentifier.PORT_RS485:return "RS485";caseCommPortIdentifier.PORT_SERIAL:return "Serial";default:return "unknown type";

}

}/***@returnA HashSet containing the CommPortIdentifier for all serial ports

* that are not currently being used.*/

public static HashSetgetAvailableSerialPorts() {

HashSet h = new HashSet();

@SuppressWarnings("rawtypes")

Enumeration thePorts= CommPortIdentifier.getPortIdentifiers();//可以找到系统的所有的串口,每个串口对应一个CommPortldentifier

while(thePorts.hasMoreElements()) {

CommPortIdentifier com=(CommPortIdentifier) thePorts

.nextElement();switch(com.getPortType()) {case CommPortIdentifier.PORT_SERIAL://type of the port is serial

try{

CommPort thePort= com.open("CommUtil", 50);//open the serialPort

thePort.close();

h.add(com);

}catch(PortInUseException e) {

System.out.println("Port, " +com.getName()+ ", is in use.");

}catch(Exception e) {

System.err.println("Failed to open port " +com.getName());

e.printStackTrace();

}

}

}returnh;

}public static SerialPort connect(String portName) throwsException {

SerialPort serialPort= null;

CommPortIdentifier portIdentifier=CommPortIdentifier

.getPortIdentifier(portName);//initializes of port operation

if(portIdentifier.isCurrentlyOwned()) {

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

}else{

CommPort commPort= portIdentifier.open(portName, 2000);//the delay//time of//opening//port

if (commPort instanceofSerialPort) {

serialPort=(SerialPort) commPort;

serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8,

SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);//serial//communication//parameters//setting

InputStream inputStream =serialPort.getInputStream();//OutputStream outputStream = serialPort.getOutputStream();//(new Thread(new SerialWriter(outputStream))).start();

serialPort.addEventListener(newSerialReader(inputStream));

serialPort.notifyOnDataAvailable(true);

}

}returnserialPort;

}/*** not necessary to send command in new thread, but the serialPort only has

* one instance

*

*@paramserialPort

*@paramstring*/

public static voidsendMessage(SerialPort serialPort, String string) {try{

OutputStream outputStream=serialPort.getOutputStream();

(new Thread(new SerialWriter(outputStream, string))).start();//send//command//in//the//new//thread

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

e.printStackTrace();

}

}/*** Handles the input coming from the serial port. A new line character is

* treated as the end of a block in this example.*/

public static class SerialReader implementsSerialPortEventListener {privateInputStream in;publicSerialReader(InputStream in) {this.in =in;

}public voidserialEvent(SerialPortEvent arg0) {byte[] buffer = new byte[1024];try{

Thread.sleep(500);//the thread need to sleep for completed//receive the data

if (in.available() > 0) {

in.read(buffer);

}

System.out.println(newString(buffer));

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

e.printStackTrace();

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

e.printStackTrace();

}

}

}/** */

public static class SerialWriter implementsRunnable {

OutputStream out;

String commandString;publicSerialWriter(OutputStream out, String commandString) {this.out =out;this.commandString =commandString;

}public voidrun() {while (true) {try{

Thread.sleep(3000);//an interval of 3 seconds to sending//data

out.write(commandString.getBytes());

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

e.printStackTrace();

}catch(InterruptedException e1) {//TODO Auto-generated catch block

e1.printStackTrace();

}

}

}

}public static voidmain(String[] args) {

listAvailablePorts();try{

sendMessage(connect("/dev/ttyUSB0"), "P");

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

e.printStackTrace();

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值