java 操作comm(串口)入门问题
javaComm20-win32你操作comm的需要的资料和相关的配置文件,相关的配置方法如(javaComm20-win32的里面也有相关的介绍):把win32com.dll复制到java.home/bin下;把javax.comm.properties复制到java.home/lib下;把comm.jar添加到你classPath下。前面两个都是非常重要的。
Java,comm是专门为Java读取串口信息的而编写的API,这个既可以读取到串口的信息,也可以进行相关数据的写入到对应的串口中。这个一般刚刚开始,使用简单的代码,进行读取的时候,可能会什么都没有发现,这个是应该,你的代码的问题,网上有的人说是,电脑配置了这个环境,机器要重新的启动,但是我测试了,这个是不对的。这个是代码的问题导致的。看看下面的代码,这个代码的下载的文件中自带的测试的代码:
import java.io.*;import java.util.*;import javax.comm.*;public class SimpleRead implements Runnable, SerialPortEventListener { static CommPortIdentifier portId; static Enumeration portList; InputStream inputStream; SerialPort serialPort; Thread readThread; public static void main(String[] args) {/*CommDriver driver = null; String driverName = "com.sun.comm.Win32Driver"; try { driver = (CommDriver) Class.forName(driverName).newInstance(); driver.initialize(); } catch (InstantiationException e){ e.printStackTrace(); }catch (IllegalAccessException e){ e.printStackTrace(); }catch (ClassNotFoundException e){ e.printStackTrace(); }*/ portList = CommPortIdentifier.getPortIdentifiers(); System.out.println("flag:"+portList.hasMoreElements()); while (portList.hasMoreElements()) { portId = (CommPortIdentifier) portList.nextElement(); if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) { if (portId.getName().equals("COM1")) { SimpleRead reader = new SimpleRead(); } } } } public SimpleRead() { try { serialPort = (SerialPort) portId.open("SimpleReadApp", 2000); } catch (PortInUseException e) {e.printStackTrace();} try { inputStream = serialPort.getInputStream(); } catch (IOException e) {e.printStackTrace();}try { serialPort.addEventListener(this);} catch (TooManyListenersException e) {e.printStackTrace();} serialPort.notifyOnDataAvailable(true); try { serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); } catch (UnsupportedCommOperationException e) { e.printStackTrace(); } readThread = new Thread(this); readThread.start(); } public void run() { try { Thread.sleep(20000); } catch (InterruptedException e) { e.printStackTrace(); } } 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: byte[] readBuffer = new byte[20]; try { while (inputStream.available() > 0) { int numBytes = inputStream.read(readBuffer); } System.out.print(new String(readBuffer)); } catch (IOException e) { e.printStackTrace(); } break; } }}详细的请看:http://www.iteye.com/topic/64859#