在Windows系统下,用Java开发串口通信相关的程序时,需要用到几个文件。
(1)win32com.dll 要放在jdkjrein目录下。
(2)comm.jar 和javax.comm.properties要放在jdkjrelib目录下。
下面是如何使用SerialPort的Demo:
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package tina; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.TooManyListenersException; import java.util.logging.Level; import java.util.logging.Logger; import javax.comm.CommPortIdentifier; import javax.comm.NoSuchPortException; import javax.comm.PortInUseException; import javax.comm.SerialPort; import javax.comm.SerialPortEvent; import javax.comm.SerialPortEventListener; import javax.comm.UnsupportedCommOperationException; import javax.swing.JOptionPane; /** * * @author Tina */ public class DemoCom implements SerialPortEventListener { private static final String PORT_NAME = "COM4"; //串口号 private static final int PORT_BAUDRATE = 115200; //波特率 private static DemoCom instance; private final SerialPort mSerialPort; private final PrintWriter mWriter; private final InputStream mInputStream; private OnMsgArrivedListener mListener; private final StringBuffer buffer = new StringBuffer(); public interface OnMsgArrivedListener { //收到字符 void OnMsgArrived(char c); } private DemoCom(CommPortIdentifier portId, int baudrate) throws PortInUseException, UnsupportedCommOperationException, IOException { mSerialPort = (SerialPort) portId.open("DemoCom", baudrate); mSerialPort.setSerialPortParams(baudrate, SerialPort.DATABITS_8, //Data Bits SerialPort.STOPBITS_1, //Stop Bits SerialPort.PARITY_NONE); //无校验 mSerialPort.notifyOnDataAvailable(true); OutputStream mOutputStream = mSerialPort.getOutputStream(); mInputStream = mSerialPort.getInputStream(); mWriter = new PrintWriter(mOutputStream); } public static DemoCom getInstance() { if (instance == null) { CommPortIdentifier portId; try { portId = (CommPortIdentifier) CommPortIdentifier.getPortIdentifier(PORT_NAME); instance = new DemoCom(portId, PORT_BAUDRATE); } catch (NoSuchPortException ex) { JOptionPane.showMessageDialog(null, "没有找到串口" + PORT_NAME + ",请确认USB线是否连接好!"); System.exit(0); } catch (PortInUseException ex) { JOptionPane.showMessageDialog(null, "串口" + PORT_NAME + "被占用,请关闭其他可能占用的应用软件!"); System.exit(0); } catch (UnsupportedCommOperationException ex) { JOptionPane.showMessageDialog(null, "串口" + PORT_NAME + "打开失败:" + ex.getMessage()); System.exit(0); } catch (IOException ex) { JOptionPane.showMessageDialog(null, "串口" + PORT_NAME + "打开失败:" + ex.getMessage()); System.exit(0); } } return instance; } @Override public void serialEvent(SerialPortEvent spe) { if (spe.getEventType() == SerialPortEvent.DATA_AVAILABLE) { try { while (mInputStream.available() > 0) { //处理数据 int c = mInputStream.read(); buffer.append((char) c); //这里只是将数据传到其他需要监听串口数据的地方 if (mListener != null) { mListener.OnMsgArrived((char) c); } } } catch (IOException ex) { Logger.getLogger(PortFixture.class.getName()).log(Level.SEVERE, null, ex); } } } public String sendAndGet(String command, int delayMs) { //发送命令 if (mWriter != null) { mWriter.println(command); mWriter.flush(); } //延时 try { Thread.sleep(delayMs); } catch (InterruptedException ex) { Logger.getLogger(PortFixture.class .getName()).log(Level.SEVERE, null, ex); } //查看回复的数据 if (!buffer.toString().isEmpty()) { //如果buffer非空 String str = buffer.toString(); System.out.println(buffer.toString()); buffer.delete(0, buffer.length());//读完之后清空 return str; } else { return ""; } } public void send(String command) { buffer.delete(0, buffer.length());//发送之前清空 try { Thread.sleep(10); } catch (InterruptedException ex) { Logger.getLogger(PortFixture.class.getName()).log(Level.SEVERE, null, ex); } //发送命令 if (mWriter != null) { mWriter.println(command); mWriter.flush(); } } public void open() { try { mSerialPort.addEventListener(this); } catch (TooManyListenersException ex) { Logger.getLogger(PortFixture.class .getName()).log(Level.SEVERE, null, ex); } //打开串口后,做一些处理 if (!sendAndGet("reset", 1000).toLowerCase().contains("ok")) { JOptionPane.showMessageDialog(null, "无法复位!"); System.exit(0); } } public void close() { if (mWriter != null) { mWriter.close(); } if (mInputStream != null) { try { mInputStream.close(); } catch (IOException ex) { Logger.getLogger(PortFixture.class.getName()).log(Level.SEVERE, null, ex); } } if (mSerialPort != null) { mSerialPort.close(); } } public void setOnMsgArrivedListener(OnMsgArrivedListener listener) { mListener = listener; } }