Java 串口通信
2016-07-18 18:04
246 查看
在Windows系统下,用Java开发串口通信相关的程序时,需要用到几个文件。
(1)win32com.dll 要放在jdk\jre\bin目录下。
(2)comm.jar 和javax.comm.properties要放在jdk\jre\lib目录下。
下面是如何使用SerialPort的Demo:
(1)win32com.dll 要放在jdk\jre\bin目录下。
(2)comm.jar 和javax.comm.properties要放在jdk\jre\lib目录下。
下面是如何使用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; } }
相关文章推荐
- netdevgirl.eclipse创建maven javaweb项目
- eclipse里面已经提交的svn提交
- spring 事务管理的学习总结
- Eclipse没有编译class文件
- 【spring 7】spring和Hibernate的整合:声明式事务
- 【spring 7】spring和Hibernate的整合:声明式事务
- spring mvc异常统一处理(ControllerAdvice注解)
- 【转-整理】spring中scope的singleton和prototype区别
- hdu1753java(大数相加)---BigDecimal类
- 你不知道的Java类
- javabean解决jsp中中文乱码问题
- Spring中使用xml配置bean的细节
- DecimalFormat对数值格式化的舍入问题——RoundingMode
- 交换两个变量的值,不使用第三个变量的四种方法
- Eclipse常用快捷键
- java入门第一季_1.5_流程控制语句
- java中几种常用的对象类型(po,vo,bo,dto)
- java语言基础入门——类的介绍
- java基础01 从Java的继承谈 重载、重写(覆盖)、隐藏
- JAVA JSON数组解析