Ubuntu 系统下java rxtx 开发串口通讯程序

        最近做了Ubuntu系统下关于Java Rxtx 串口开发的项目,对于Rxtx有一些经验和大家分享一下。 获取系统可用串口,可以设置屏蔽掉ttyUSB0-ttyUSB3(因为可能被系统占用,也可以不屏蔽).开发主要针对USB-SerialPort,直接是串口的话,将ttyUSB修改为ttyS。

 

                 /**
		 * 列出可用串口列表
		 * @return
		 */
		public String getAvailableSerialPortsName() {
                               String ttyUSB = null;
				@SuppressWarnings("rawtypes")
				Enumeration thePorts = CommPortIdentifier.getPortIdentifiers();
		                     while (thePorts.hasMoreElements()) {
					CommPortIdentifier com = (CommPortIdentifier) thePorts.nextElement();
					switch (com.getPortType()) {
					case CommPortIdentifier.PORT_SERIAL:
						CommPort thePort = null;
						try {//过滤COM1-3
							thePort = com.open("CommUtil", 2000);
							if (!Pattern.compile("ttyUSB[0-3]\\b").matcher(com.getName()).matches()) {								
								ttyUSB = com.getName();
							}
						} catch (PortInUseException e) {
							e.printStackTrace();						
						} catch (Exception e) {
							System.out.println("Failed to open port " + com.getName());
						} finally {
							if (thePort != null) {
								thePort.close();
							}
						}
					}
				}
				return ttyUSB;
			}


进行监听获取到的需要通讯的串口,其中ttyUSB为需要打开的串口/dev/ttyUSB(在windows下使用,只要将ttyUSB换成COM)。

 

 

 

 

        /** 检测系统中可用的通讯端口类 */
	static CommPortIdentifier portId;
	/** Enumeration 为枚举型类,在java.util中 */
	@SuppressWarnings("rawtypes")
	static Enumeration portList;
	InputStream inputStream; 
	/** 声明RS-232串行端口的成员变量 */
	SerialPort serialPort;
	OutputStream outputStream;
	/**
	 * 点击按扭所触发的事件:打开串口,并监听串口.
         * @author Luckyion
         */
	public void actionPerformed(String ttyUSB)
	{
		/**获取系统中所有的通讯端口 */
		portList=CommPortIdentifier.getPortIdentifiers();
		/** 用循环结构找出串口 */
		while (portList.hasMoreElements()){
			/**强制转换为通讯端口类型*/
			portId=(CommPortIdentifier)portList.nextElement();
			if(portId.getPortType() == CommPortIdentifier.PORT_SERIAL){
				//USB串口1
				if (portId.getName().equals(ttyUSB)) {
					try {
						serialPort = (SerialPort) portId.open("ReadComm", 2000);
						/**设置串口监听器*/
						serialPort.addEventListener(this);
						/** 侦听到串口有数据,触发串口事件*/	
						serialPort.notifyOnDataAvailable(true);
					}
					catch (PortInUseException e) {
						e.printStackTrace();
					}					
					catch (TooManyListenersException e) { 
						e.printStackTrace();
					}
									
				}
				//if end
			} //if end
		} //while end
	} //actionPerformed() end

       打开串口后,就可以通过串口和串口设备进行通讯了。

 

 

        /**
	 * 串口监听器触发的事件,设置串口通讯参数,读取数据
	 * @author Luckyion
	 */
	public void serialEvent(SerialPortEvent event) {
		/**设置串口通讯参数:波特率、数据位、停止位、奇偶校验*/
		try { 
			serialPort.setSerialPortParams(9600,
					SerialPort.DATABITS_8,
					SerialPort.STOPBITS_1,
					SerialPort.PARITY_NONE);
		}
		catch (UnsupportedCommOperationException e) {
			e.printStackTrace();
		}
		try {
				inputStream = serialPort.getInputStream();
			}
			catch (IOException e) {
				e.printStackTrace();
			}
			try {
				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:
						/** 从线路上读取数据流 */
						//String bytess="";
						while (inputStream.available() > 0) {
							int numBytes = inputStream.read();
            		} //while end					      		
		    }
		}
		catch (IOException e) { 
			e.printStackTrace();
		}
	} 

        若要进行串口写操作,使用SerialOutputStream。

 

 

/**
	 * 写入串口数据
	 * @author Luckyion
	 */
	protected void writes(byte[] b){
		try {
			outputStream = serialPort.getOutputStream();
			outputStream.write(b);
			outputStream.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

刚开始学着写博客,写的不好,请大家谅解哈。

 

 

 

 

 

 

 

 

 

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值