java串口通訊第一次使用,找的資料都比較麻煩,一時沒有理出頭緒,自己在示例的基礎上整理了一個簡單的應答示例,比較簡陋,但演示了java串口通訊的基本過程。
package com.garfield.comm; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import javax.comm.CommPortIdentifier; import javax.comm.SerialPort; public class SimpleCommIO implements Runnable { static CommPortIdentifier portId; static String cmdHand = "I\r\n"; static String cmdWeight = "WX\r\n"; static SerialPort serialPort; static OutputStream outputStream; static String comm="COM11"; InputStream inputStream; Thread readThread; public void run() { while (true) { try { byte[] readBuffer = new byte[200]; try { while (inputStream.available() > 0) { int numBytes = inputStream.read(readBuffer); System.out.print("收到數據:"+new String(readBuffer)); } } catch (IOException e) { e.printStackTrace(); } Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } } } public void initComm() { try{ portId = CommPortIdentifier.getPortIdentifier(comm); serialPort = (SerialPort) portId.open("SimpleCommIO",2000); outputStream = serialPort.getOutputStream(); inputStream = serialPort.getInputStream(); serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); }catch(Exception e){ e.printStackTrace(); } } public void writeComm(String cmd) { try { outputStream.write(cmd.getBytes()); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { SimpleCommIO reader = new SimpleCommIO(); reader.initComm(); Thread readThread = new Thread(reader); readThread.start(); System.out.println("發出指令:"+cmdHand); reader.writeComm(cmdHand); //暫停一會兒 try { Thread.sleep ( 2000 ) ; } catch (InterruptedException ie) { } System.out.println("發出指令:"+cmdWeight); reader.writeComm(cmdWeight); } }
另注配置:
將javacomm20-win32 .zip下載的文件解壓縮后,在\javacomm20-win32\commapi目錄下有必需的三個文件:
comm.jar,javax.comm. properties和win32comm.dll。
將文件comm.jar拷貝到%JAVA_HOME%\jre\lib\ext;
文件 javax.comm. properties拷貝到%JAVA_HOME%\jre\lib;
文件win32comm.dll拷貝到%JAVA_HOME%\bin。
注意%JAVA_HOME%是jdk的路徑,而非jre。