java RXTXcomm.jar的串口通信

RXTXcomm.jar包下载地址

链接: https://pan.baidu.com/s/1-Cjg4mu8pdL6SDVdNlf1eA
提取码: ete4

RXTXcomm.jar的配置

将压缩包解压
然后将文件夹里的rxtxSerial.dll、rxtxParallel.dll复制到<JAVA_HOME>\jre\bin目录下
同时将RXTXcomm.jar复制到<JAVA_HOME>\jre\lib\ext目录下
到eclipse中右击项目点击Build Path,再点击Configure Build Path ,然后点击 Libraries,然后点击 Add External JARs,最后选择<JAVA_HOME>/jre/lib/ext目录下的RXTXcomm.jar,点击打开,点击OK。

代码示例

串口通信连接类

// An highlighted block
package Tool;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.NoSuchPortException;
import gnu.io.SerialPort;
import gnu.io.UnsupportedCommOperationException;

public class SerialTool
{
private static SerialTool st=null;
static{
	if(st==null)
	st=new SerialTool();
}
private SerialTool(){}
public static SerialTool getSerialTool() {
    if (st == null) {
        st = new SerialTool();
    }
    return st;
}
public static final ArrayList<String> findPort()
{
	 Enumeration<CommPortIdentifier> portList = CommPortIdentifier.getPortIdentifiers();    
     ArrayList<String> portNameList = new ArrayList<>();
     //将可用串口名添加到List并返回该List
     while (portList.hasMoreElements()) {
         String portName = portList.nextElement().getName();
         portNameList.add(portName);
     }
     return portNameList;
}
public static final SerialPort openPort(String portName, int baudrate) throws Exception {

   try {
       //通过端口名识别端口
       CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
       //打开端口,并给端口名字和一个timeout(打开操作的超时时间)
       CommPort commPort = portIdentifier.open(portName, 2000);
       //判断是不是串口
       if (commPort instanceof SerialPort) {    
           SerialPort serialPort = (SerialPort) commPort; 
           try {                        
               //设置一下串口的波特率等参数
               serialPort.setSerialPortParams(baudrate, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);                              
           } catch (UnsupportedCommOperationException e) {  
                e.printStackTrace();
           }
           System.out.println("Open " + portName + " sucessfully !");
           return serialPort;
       
       }        
       else {
           //不是串口
           return null;
       }
   } catch (NoSuchPortException e1) {
     e1.printStackTrace();
}
  
   return null;
   
}

public static void closePort(SerialPort serialPort) {
    if (serialPort != null) {
        serialPort.close();
        System.out.println("Close " + serialPort + " sucessfully !");
        serialPort = null;
    }
}
public static void sendToPort(SerialPort serialPort, byte[] order) {
	 
    OutputStream out = null;
    try {
        out = serialPort.getOutputStream();
        out.write(order);
        out.flush();
        
    } catch (Exception e) {
        e.printStackTrace(); 
    } finally {
        try {
            if (out != null) {
                out.close();
                out = null;
            }                
        } catch (Exception e) {
             e.printStackTrace();
        }
    }
    
}
public static byte[] read(SerialPort serialPort)  {
	 
    InputStream in = null;
    byte[] bytes = null;
    try {
        in = serialPort.getInputStream();
        int bufflenth = in.available();        //获取buffer里的数据长度
        
        while (bufflenth != 0) {                             
            bytes = new byte[bufflenth];    //初始化byte数组为buffer中数据的长度
            in.read(bytes);
            bufflenth = in.available();
            //bufflenth--;
        } 
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (in != null) {
                in.close();
                in = null;
            }
        } catch(Exception e) {
           e.printStackTrace();
        }
    }
    return bytes;
}

}




c
主方法:

// An highlighted block

import java.util.TooManyListenersException;

import Tool.SerialTool;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;

public class Test
{
static SerialPort sp=null;
public static void main(String[] args){
try{
		
			sp=SerialTool.openPort("COM5", 9600);
			if(sp!=null)
			{
				
				
				try {
					//给串口添加事件监听
					sp.addEventListener(new SerialPortEventListener() {
						@Override
						public void serialEvent(SerialPortEvent arg0) {
							if(arg0.getEventType() == SerialPortEvent.DATA_AVAILABLE) {//数据通知
								byte[] bytes = SerialTool.read(sp);//从串口读取数据
								//System.out.println("收到的数据长度:"+bytes.length);
								String data=new String(bytes);
									System.out.println("收到的数据:"+data);
									SerialTool.sendToPort(sp, data.getBytes());//向串口写入数据
							}
						}
					});
				} catch (TooManyListenersException e) {
					e.printStackTrace();
				}
				sp.notifyOnDataAvailable(true);//串口有数据监听
				sp.notifyOnBreakInterrupt(true);//中断事件监听
			}
			}
			catch(Exception ex){
				ex.printStackTrace();	
			}
		

		
			//SerialTool.closePort(sp);关闭端口通信
		
	}
} 


说明

代码和jar包亲测能够直接运行。
注意事项:请一定一定一定使用监听器来接收串口数据,小编之前自己写了个线程来读取串口数据,结果一直会出现数据丢失的问题。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值