java 串口通信的例子(RXTX)

近期要做一个运行与安卓系统之上,与检测仪器进行串口通信的软件,折腾了好几天,现在整理了一个串口通信的完整例子,引用的是RXTX相关的包:

类结构:


SPComm.java:   通信主体

SPCommTest.java:  调用者


1.  SPComm.java

import gnu.io.CommPortIdentifier;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import gnu.io.UnsupportedCommOperationException;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.TooManyListenersException;


public class SPComm implements Runnable, SerialPortEventListener {

	// 检测系统中可用的通讯端口类
	private static CommPortIdentifier portId;
	private static Enumeration<CommPortIdentifier> portList;
	// 输入输出流
	public static InputStream inputStream;
	public static OutputStream outputStream;
	// RS-232的串行口
	public static SerialPort serialPort;
	public static Thread commThread;
	
	//初始化串口
	public static void init() {
		portList = CommPortIdentifier.getPortIdentifiers();
		while (portList.hasMoreElements()) {
			portId = (CommPortIdentifier) portList.nextElement();
			if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL){
				if (portId.getName().equals("COM8")) {
					try {
						serialPort = (SerialPort) portId.open("SerialPort-Test", 2000);
						serialPort.addEventListener(new SPComm());
						serialPort.notifyOnDataAvailable(true);
						/* 设置串口通讯参数 */
						serialPort.setSerialPortParams(19200,SerialPort.DATABITS_8, SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
						
						outputStream = serialPort.getOutputStream();
						inputStream = serialPort.getInputStream();
					} catch (PortInUseException e) {
						e.printStackTrace();
					} catch (TooManyListenersException e) {
						e.printStackTrace();
					} catch (UnsupportedCommOperationException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					} 
				}
			}
		}
	}
	/**
	 * 实现接口SerialPortEventListener中的方法 读取从串口中接收的数据
	 */
	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://获取到串口返回信息
        	int newData = 0;
        	int i = 0;
        	
        	do{
				try{
					newData = inputStream.read();
					//对数据进行处理,省略...
					
					i++;
					if(i == 24){ //根据实际需求,在适当的时候设置结束条件
						newData = -1;
					}
					
				}catch(IOException e){
					return;
				}
			}
			while(newData != -1);
        	
        	serialPort.close();//这里一定要用close()方法关闭串口,释放资源
        	
			break;
		default:
			break;
		}
	}
	
	//向串口发送信息方法
	public static void sendMsg(){
		String msg = "xxxxxxxxxxxxxx";//要发送的命令
		try {
		    outputStream.write(hexStringToBytes(msg));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void run(){        
        init();
    	sendMsg();
    	
    }
	
}


2.  SPCommTest.java
public class SPCommTest {
	public static void main(String[] args){
		Thread spcommThread = new Thread(new SPComm());
		spcommThread.setName("Thread-MyThread");
		spcommThread.start();
	
	}
}


运行SPComm.java即可。




  • 0
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 19
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 19
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小鹰信息技术服务部

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值