java 串口操作 与 zigbee通过串口通信

使用 javax.comm

1、安装:把javax.comm 解压后,复制 comm.jar javax.comm.properties win32.dll 到jdk 和 jre 下。

2、获取端口列表:

CommPortIdentifier portId;
		
Enumeration en = CommPortIdentifier.getPortIdentifiers();
while (en.hasMoreElements()) {
    portId = (CommPortIdentifier) en.nextElement();
    if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
        System.out.println(portId.getName());
    }
}

3、读取端口数据:

CommPortIdentifier portId = CommPortIdentifier.getPortIdentifier("COM1");
SerialPort sPort = (SerialPort) portId.open("", 1000);
sPort.setSerialPortParams(115200, 8, 1, SerialPort.PARITY_NONE);
InputStream inputStream = sPort.getInputStream();
byte[] readBuffer;

while(true){
	try {
		while (inputStream.available() > 0) {
			readBuffer = new byte[inputStream.available()];
			inputStream.read(readBuffer);
			System.out.println(new String(readBuffer));
		}
	} catch (IOException e) {
	}
}

 

 

发表评论