串口通信Demo

1.下载串口通信所需的jar包和库文件

RXTXcomm.jar

rxtxParallel.dll

rxtxSerial.dll

2.将rxtxParallel.dll和rxtxSerial.dll拷贝到JDK安装目录,如C:\Program Files\Java\jdk1.5.0_22\bin

3.将RXTXcomm.jar拷贝到项目相关目录

创建SerialManager.java类文件

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.NoSuchPortException;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;

public class SerialManager implements SerialPortEventListener {

	private InputStream in;
	private OutputStream out;
	private String portName;

	/**
	 * 连接串口
	 * @param portName
	 * @throws Exception
	 */
	private void connect(String portName) throws Exception{
		this.portName = portName;
		String message = "";
		try {
			CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
			if(portIdentifier.isCurrentlyOwned()){
				message = "The " + portName +" is currently in use";
				throw new Exception(message);
			}
			
			CommPort commPort =  portIdentifier.open("Serial_Communication" + portName, 3000);
			if (commPort instanceof SerialPort) {
				SerialPort serialPort = (SerialPort)commPort;
				
				//波特率:9600,数据位:8,停止位:1,奇偶校验:无
				serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
				
				in = serialPort.getInputStream();
				out = serialPort.getOutputStream();
				
				serialPort.addEventListener(this);
				serialPort.notifyOnDataAvailable(true);
			} else {
				message = "The " + portName + " is invalid serial port. Opening " + portName + " is failed.";
				throw new Exception(message);
			}
		} catch(NoSuchPortException e) {
			message = "The " + portName + " isn't exits. Opening " + portName + " is failed.";
			throw new Exception(message);			
		} catch(PortInUseException e) {
			message = "The " + portName + " is currently in use";
			throw new Exception(message);						
		} catch(Exception e) {
			message = "It's failed to open " + portName+ " because of " + e.getMessage();
			throw new Exception(message);			
		}
	}
	
	/**
	 * 向串口发送消息
	 * @param msg
	 * @return
	 * @throws IOException
	 * @throws InterruptedException
	 * @throws Exception
	 */
	public boolean sendMessage(String msg) throws IOException, InterruptedException, Exception {
		String message = "";
		if (out == null){  //端口如果没有打开,则进行打开			
			message = "It's failed to send packet(%s) because the %s can't be opened.";
			message = String.format(message, msg, portName);
			System.out.println(message);
			return false;			
		}
		out.write(msg.getBytes());
		message = "It's successful to send packet(%s) to port %s.";
		message = String.format(message, msg, portName);
		System.out.println(message);
		return true;
	}
	
	/**
	 * 实现SerialPortEventListener接口中的方法
	 * 当串口有数据时,读出数据
	 */
	public void serialEvent(SerialPortEvent event) {
		int eventType = event.getEventType();
		switch(eventType){
			case SerialPortEvent.DATA_AVAILABLE:			
				try{				
					byte[] buffer = new byte[2048];
					int length = this.in.read(buffer);
					if (length > 0) {
						byte[] data = new byte[length];
						System.arraycopy(buffer, 0, data, 0, length);
						System.out.println("Receive data:" + new String(data));
					}
				}catch(Exception e){
					
				}
				break;
			case SerialPortEvent.OE:
				System.out.println("Overrun Error!");
				break;
			case SerialPortEvent.FE:
				System.out.println("Framing Error!");
				break;
			case SerialPortEvent.PE:
				System.out.println("Parity Error!");
				break;
		}
	}

	/**
	 * 测试程序
	 * @param args
	 * @throws Exception
	 */
	public static void main(String[] args) throws Exception {
		SerialManager ser = new SerialManager();
		ser.connect("COM1");
		//ser.sendMessage("Hello Serial."); //测试发送
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		while(true){
			System.out.println("输入信息,按回车键发送:");
			String message = br.readLine();
			if("quit".equals(message)){
				System.exit(0); //退出程序
			}
			ser.sendMessage(message);
		}
	}
}


运行程序如下图


串口调试助手发送程序如下图



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值