Java实现串口通信

本程序测试环境:

jdk版本:1.6   64位

rxtx for java版本:Windows 64位

下载rxtx,

第一步:把RXTXcomm.jar放在jdk的jdk/jre/lib/ext目录下

第二步:把rxtxParallel.dll、rxtxSerial.dll放在jdk/jre/bin目录下

第三步:把rxtxParallel.dll、rxtxSerial.dll放在jdk/bin目录下

第三步:复制以下代码并保存到jdk/bin/目录下,用Main.java作为文件名

public class Main {
	public static void main(String[] args) {
		java.lang.System.out.println("Hello World!");
		java.util.Enumeration enumeration = gnu.io.CommPortIdentifier.getPortIdentifiers();
		while (enumeration.hasMoreElements()) {
			java.lang.Object object = enumeration.nextElement();
			if (object instanceof gnu.io.CommPortIdentifier) {
				gnu.io.CommPortIdentifier commPortIdentifier = (gnu.io.CommPortIdentifier) object;
				java.lang.String name = commPortIdentifier.getName();
				java.lang.System.out.println(name);
			}
		}
		gnu.io.CommPortIdentifier commPortIdentifier = null;
		try {
			commPortIdentifier = gnu.io.CommPortIdentifier.getPortIdentifier("COM3");
		} catch (gnu.io.NoSuchPortException noSuchPortException) {
			noSuchPortException.printStackTrace();
		}
		if (commPortIdentifier != null) {
			if (commPortIdentifier.isCurrentlyOwned()) {
				java.lang.System.out.println("Error: Port is currently in use");
			} else {
				gnu.io.CommPort commPort = null;
				try {
					 commPort = commPortIdentifier.open("COMthree", 2000);
				} catch (gnu.io.PortInUseException portInUseException) {
					portInUseException.printStackTrace();
				}
				if (commPort instanceof gnu.io.SerialPort) {
					try {
						gnu.io.SerialPort serialPort = (gnu.io.SerialPort) commPort;
						serialPort.setSerialPortParams(57600, gnu.io.SerialPort.DATABITS_8, gnu.io.SerialPort.STOPBITS_1, gnu.io.SerialPort.PARITY_NONE);
						java.io.InputStream inputStream = serialPort.getInputStream();
						byte[] buffer = new byte[1024];
						int len = -1;
						while ((len = inputStream.read(buffer)) > -1) {
							java.lang.String receivedResult = new java.lang.String(buffer, 0, len);
							if (!receivedResult.equals("")) {
								java.lang.System.out.print(receivedResult);
							}
						}
					} catch (gnu.io.UnsupportedCommOperationException unsupoortedCommOperationException) {
						unsupoortedCommOperationException.printStackTrace();
					} catch (java.io.IOException ioException) {
						ioException.printStackTrace();
					}
				} else {
					java.lang.System.out.println("Error: Only serial ports are handled by this example");
				}
			}
		}
	}
}

第四步:打开cmd命令行,把工作目录切换到jdk的bin/目录下

第五步:运行这个命令(.\javac.exe Main.java)

第六步:运行这个命令(.\java.exe Main)

之后用串口助手发送信息就可以通信了

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值