Java读取串口的方法

		Enumeration portList = CommPortIdentifier.getPortIdentifiers();
		if (portList.hasMoreElements()) {
			// 如果找到了串口
			msgLabel.setText("串口接口调用成功");
		} else {
			msgLabel.setText("没有找到可用的串口");
		}
		while (portList.hasMoreElements()) {
			CommPortIdentifier portId = (CommPortIdentifier) portList.nextElement();
			if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
				comListCombo.add(portId.getName());
				comListCombo.setText(portId.getName());
			}
		}


portList = CommPortIdentifier.getPortIdentifiers();
if (portList.hasMoreElements()) {
	// 如果找到了串口
	msgLabel.setText("串口接口调用成功");
} else {
	msgLabel.setText("没有找到可用的串口");
}
while (portList.hasMoreElements()) {

	portId = (CommPortIdentifier) portList.nextElement();
	if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
		String selectedCom = comListCombo.getText();
		if (portId.getName().equals(selectedCom)) { // 端口名 //TODO
			// if (portId.getName().equals("COM1")) { // 端口名 //TODO
			try {
				serialPort = (SerialPort) portId.open("ReadComm", 10000);
				serialPort.setSerialPortParams(115200, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
				// setStatus("已打开端口COM7 ,正在接收数据..... ");
				msgLabel.setText("已打开串口 , 正在接收数据.....");
				// openComBtn.setEnabled(false);
				openComBtn.setText("关闭串口");
				comPortIsOpened = true;
				serialPort.addEventListener(new SerialPortEventListener() {

					@Override
					public void serialEvent(SerialPortEvent arg0) {
						byte[] readBuffer = new byte[1024];
						int numBytes = 0;
						String readStr = "";
						try {
							inputStream = serialPort.getInputStream();
						} catch (Exception e) {
							e.printStackTrace();
						}
						try {
							while (inputStream.available() > 0) {
								numBytes = inputStream.read(readBuffer);
							}

						} catch (Exception e) {
							// e.printStackTrace();
							Display.getDefault().syncExec(new Runnable() {
								public void run() {
									macText.setText("ComOUT");
									qrCodeText.setText("ComOUT");
									openComBtn.setEnabled(true);
									createQrCodeBtn.setEnabled(false);
									btnmac.setEnabled(false);
									// setStatus("串口已经拔出,请重新插入串口后打开");

									msgLabel.setText("串口已经拔出,请重新插入串口后打开");

									openComBtn.setText("打开串口");
									qrCodeLabel.setImage(SWTResourceManager.getImage(MainWindow.class, "/"
											+ ConfigUtil.dsmLogoImage));
								};
							});
							serialPort.close();
							outputStream = null;
							inputStream = null;
							comPortIsOpened = false;
						}
					}
				});

				serialPort.notifyOnDataAvailable(true);

			} catch (Exception e5) {
				e5.printStackTrace();
			}
		}
	}

先放着。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值