comport java_java read com port

java 读取串口的技术

       1、rxtx 

   http://rxtx.qbang.org/wiki/index.php/Download

package fpx.grs.aliexpress.com;

import java.io.IOException;

import java.io.InputStream;

import java.util.Enumeration;

import java.util.TooManyListenersException;

import gnu.io.CommPortIdentifier;

import gnu.io.PortInUseException;

import gnu.io.SerialPort;

import gnu.io.SerialPortEvent;

import gnu.io.SerialPortEventListener;

import gnu.io.UnsupportedCommOperationException;

public class SimpleRead implements Runnable, SerialPortEventListener {

static CommPortIdentifier portId;

static Enumeration portList;

InputStream inputStream;

SerialPort serialPort;

Thread readThread;

public static void main(String[] args) {

portList = CommPortIdentifier.getPortIdentifiers();

while (portList.hasMoreElements()) {

portId = (CommPortIdentifier) portList.nextElement();

if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {

if (portId.getName().equals("COM4")) {

// if (portId.getName().equals("/dev/term/a")) {

SimpleRead reader = new SimpleRead();

}

}

}

}

public SimpleRead() {

try {

serialPort = (SerialPort) portId.open("SimpleReadApp", 2000);

} catch (PortInUseException e) {System.out.println(e);}

try {

inputStream = serialPort.getInputStream();

} catch (IOException e) {System.out.println(e);}

try {

serialPort.addEventListener(this);

} catch (TooManyListenersException e) {System.out.println(e);}

serialPort.notifyOnDataAvailable(true);

try {

serialPort.setSerialPortParams(9600,

SerialPort.DATABITS_8,

SerialPort.STOPBITS_1,

SerialPort.PARITY_NONE);

} catch (UnsupportedCommOperationException e) {System.out.println(e);}

readThread = new Thread(this);

readThread.start();

}

public void run() {

try {

Thread.sleep(20000);

} catch (InterruptedException e) {System.out.println(e);}

}

public void serialEvent(SerialPortEvent event) {

switch(event.getEventType()) {

case SerialPortEvent.BI:

case SerialPortEvent.OE:

case SerialPortEvent.FE:

case SerialPortEvent.PE:

case SerialPortEvent.CD:

case SerialPortEvent.CTS:

case SerialPortEvent.DSR:

case SerialPortEvent.RI:

case SerialPortEvent.OUTPUT_BUFFER_EMPTY:

break;

case SerialPortEvent.DATA_AVAILABLE:

byte[] readBuffer = new byte[20];

try {

while (inputStream.available() > 0) {

int numBytes = inputStream.read(readBuffer);

}

System.out.print(new String(readBuffer));

} catch (IOException e) {System.out.println(e);}

break;

}

}

}

2、jSerialComm

在rxtx基础上不需要增加系统的dll

https://github.com/Fazecast/jSerialComm/wiki

3、jssc

google的不需要依赖系统的dll

https://code.google.com/archive/p/java-simple-serial-connector/downloads

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值