基于java的串口通讯(附带实例+说明文档+测试工具)

来源:互联网 发布:java图片变成视频 编辑:程序博客网 时间:2024/05/19 04:05

现在一般的电脑都没有串口端口的了,所以还是用虚拟的串口来做测试吧。

我们用 VSPD(Virtual Serial Port Driver) 这个软件建立两个虚拟串口,COM2和COM3,名字随便起,VSPD对虚拟串口的序号没有限制,理论上可以创建无数个。


串口通信类如下:

[java] view plaincopy
  1. package org.serial;  
  2.   
  3. import java.io.BufferedInputStream;  
  4. import java.io.BufferedOutputStream;  
  5. import java.io.IOException;  
  6. import java.io.InputStream;  
  7. import java.io.OutputStream;  
  8. import java.util.Enumeration;  
  9. import java.util.TooManyListenersException;  
  10.   
  11. import javax.comm.CommPortIdentifier;  
  12. import javax.comm.PortInUseException;  
  13. import javax.comm.SerialPort;  
  14. import javax.comm.SerialPortEvent;  
  15. import javax.comm.SerialPortEventListener;  
  16.   
  17. /** 
  18.  * @项目名称 :illegalsms 
  19.  * @文件名称 :SerialPort.java 
  20.  * @所在包 :org.serial 
  21.  * @功能描述 : 
  22.  *  串口类 
  23.  * @创建者 :集成显卡   1053214511@qq.com 
  24.  * @创建日期 :2012-9-13 
  25.  * @修改记录 : 
  26.  */  
  27. public class DSerialPort implements Runnable, SerialPortEventListener {  
  28.   
  29.     private String appName = "串口通讯测试[集成显卡2012]";  
  30.     private int timeout = 2000;//open 端口时的等待时间  
  31.     private int threadTime = 0;  
  32.       
  33.     private CommPortIdentifier commPort;  
  34.     private SerialPort serialPort;  
  35.     private InputStream inputStream;  
  36.     private OutputStream outputStream;  
  37.       
  38.     /** 
  39.      * @方法名称 :listPort 
  40.      * @功能描述 :列出所有可用的串口 
  41.      * @返回值类型 :void 
  42.      */  
  43.     @SuppressWarnings("rawtypes")  
  44.     public void listPort(){  
  45.         CommPortIdentifier cpid;  
  46.         Enumeration en = CommPortIdentifier.getPortIdentifiers();  
  47.           
  48.         System.out.println("now to list all Port of this PC:" +en);  
  49.           
  50.         while(en.hasMoreElements()){  
  51.             cpid = (CommPortIdentifier)en.nextElement();  
  52.             if(cpid.getPortType() == CommPortIdentifier.PORT_SERIAL){  
  53.                 System.out.println(cpid.getName() + ", " + cpid.getCurrentOwner());  
  54.             }  
  55.         }  
  56.     }  
  57.       
  58.       
  59.     /** 
  60.      * @方法名称 :selectPort 
  61.      * @功能描述 :选择一个端口,比如:COM1 
  62.      * @返回值类型 :void 
  63.      *  @param portName 
  64.      */  
  65.     @SuppressWarnings("rawtypes")  
  66.     public void selectPort(String portName){  
  67.           
  68.         this.commPort = null;  
  69.         CommPortIdentifier cpid;  
  70.         Enumeration en = CommPortIdentifier.getPortIdentifiers();  
  71.           
  72.         while(en.hasMoreElements()){  
  73.             cpid = (CommPortIdentifier)en.nextElement();  
  74.             if(cpid.getPortType() == CommPortIdentifier.PORT_SERIAL  
  75.                     && cpid.getName().equals(portName)){  
  76.                 this.commPort = cpid;  
  77.                 break;  
  78.             }  
  79.         }  
  80.           
  81.         openPort();  
  82.     }  
  83.       
  84.     /** 
  85.      * @方法名称 :openPort 
  86.      * @功能描述 :打开SerialPort 
  87.      * @返回值类型 :void 
  88.      */  
  89.     private void openPort(){  
  90.         if(commPort == null)  
  91.             log(String.format("无法找到名字为'%1$s'的串口!", commPort.getName()));  
  92.         else{  
  93.             log("端口选择成功,当前端口:"+commPort.getName()+",现在实例化 SerialPort:");  
  94.               
  95.             try{  
  96.                 serialPort = (SerialPort)commPort.open(appName, timeout);  
  97.                 log("实例 SerialPort 成功!");  
  98.             }catch(PortInUseException e){  
  99.                 throw new RuntimeException(String.format("端口'%1$s'正在使用中!",   
  100.                         commPort.getName()));  
  101.             }  
  102.         }  
  103.     }  
  104.       
  105.     /** 
  106.      * @方法名称 :checkPort 
  107.      * @功能描述 :检查端口是否正确连接 
  108.      * @返回值类型 :void 
  109.      */  
  110.     private void checkPort(){  
  111.         if(commPort == null)  
  112.             throw new RuntimeException("没有选择端口,请使用 " +  
  113.                     "selectPort(String portName) 方法选择端口");  
  114.           
  115.         if(serialPort == null){  
  116.             throw new RuntimeException("SerialPort 对象无效!");  
  117.         }  
  118.     }  
  119.       
  120.     /** 
  121.      * @方法名称 :write 
  122.      * @功能描述 :向端口发送数据,请在调用此方法前 先选择端口,并确定SerialPort正常打开! 
  123.      * @返回值类型 :void 
  124.      *  @param message 
  125.      */  
  126.     public void write(String message) {  
  127.         checkPort();  
  128.           
  129.         try{  
  130.             outputStream = new BufferedOutputStream(serialPort.getOutputStream());  
  131.         }catch(IOException e){  
  132.             throw new RuntimeException("获取端口的OutputStream出错:"+e.getMessage());  
  133.         }  
  134.           
  135.         try{  
  136.             outputStream.write(message.getBytes());  
  137.             log("信息发送成功!");  
  138.         }catch(IOException e){  
  139.             throw new RuntimeException("向端口发送信息时出错:"+e.getMessage());  
  140.         }finally{  
  141.             try{  
  142.                 outputStream.close();  
  143.             }catch(Exception e){  
  144.             }  
  145.         }  
  146.     }  
  147.       
  148.     /** 
  149.      * @方法名称 :startRead 
  150.      * @功能描述 :开始监听从端口中接收的数据 
  151.      * @返回值类型 :void 
  152.      *  @param time  监听程序的存活时间,单位为秒,0 则是一直监听 
  153.      */  
  154.     public void startRead(int time){  
  155.         checkPort();  
  156.           
  157.         try{  
  158.             inputStream = new BufferedInputStream(serialPort.getInputStream());  
  159.         }catch(IOException e){  
  160.             throw new RuntimeException("获取端口的InputStream出错:"+e.getMessage());  
  161.         }  
  162.           
  163.         try{  
  164.             serialPort.addEventListener(this);  
  165.         }catch(TooManyListenersException e){  
  166.             throw new RuntimeException(e.getMessage());  
  167.         }  
  168.           
  169.         serialPort.notifyOnDataAvailable(true);  
  170.           
  171.         log(String.format("开始监听来自'%1$s'的数据--------------", commPort.getName()));  
  172.         if(time > 0){  
  173.             this.threadTime = time*1000;  
  174.             Thread t = new Thread(this);  
  175.             t.start();  
  176.             log(String.format("监听程序将在%1$d秒后关闭。。。。", threadTime));  
  177.         }  
  178.     }  
  179.       
  180.       
  181.     /** 
  182.      * @方法名称 :close 
  183.      * @功能描述 :关闭 SerialPort 
  184.      * @返回值类型 :void 
  185.      */  
  186.     public void close(){  
  187.         serialPort.close();  
  188.         serialPort = null;  
  189.         commPort = null;  
  190.     }  
  191.       
  192.       
  193.     public void log(String msg){  
  194.         System.out.println(appName+" --> "+msg);  
  195.     }  
  196.   
  197.   
  198.     /** 
  199.      * 数据接收的监听处理函数 
  200.      */  
  201.     @Override  
  202.     public void serialEvent(SerialPortEvent arg0) {  
  203.         switch(arg0.getEventType()){  
  204.         case SerialPortEvent.BI:/*Break interrupt,通讯中断*/   
  205.         case SerialPortEvent.OE:/*Overrun error,溢位错误*/   
  206.         case SerialPortEvent.FE:/*Framing error,传帧错误*/  
  207.         case SerialPortEvent.PE:/*Parity error,校验错误*/  
  208.         case SerialPortEvent.CD:/*Carrier detect,载波检测*/  
  209.         case SerialPortEvent.CTS:/*Clear to send,清除发送*/   
  210.         case SerialPortEvent.DSR:/*Data set ready,数据设备就绪*/   
  211.         case SerialPortEvent.RI:/*Ring indicator,响铃指示*/  
  212.         case SerialPortEvent.OUTPUT_BUFFER_EMPTY:/*Output buffer is empty,输出缓冲区清空*/   
  213.             break;  
  214.         case SerialPortEvent.DATA_AVAILABLE:/*Data available at the serial port,端口有可用数据。读到缓冲数组,输出到终端*/  
  215.             byte[] readBuffer = new byte[1024];  
  216.             String readStr="";  
  217.             String s2 = "";  
  218.               
  219.             try {  
  220.                   
  221.                 while (inputStream.available() > 0) {  
  222.                     inputStream.read(readBuffer);  
  223.                     readStr += new String(readBuffer).trim();  
  224.                 }  
  225.                   
  226.                 s2 = new String(readBuffer).trim();  
  227.                   
  228.                 log("接收到端口返回数据(长度为"+readStr.length()+"):"+readStr);  
  229.                 log(s2);  
  230.             } catch (IOException e) {  
  231.             }  
  232.         }  
  233.     }  
  234.   
  235.   
  236.     @Override  
  237.     public void run() {  
  238.         try{  
  239.             Thread.sleep(threadTime);  
  240.             serialPort.close();  
  241.             log(String.format("端口''监听关闭了!", commPort.getName()));  
  242.         }catch(Exception e){  
  243.             e.printStackTrace();  
  244.         }  
  245.     }  
  246. }  


运行测试:

[java] view plaincopy
  1. public static void main(String[] args) {  
  2.           
  3.         DSerialPort sp = new DSerialPort();  
  4.           
  5.         sp.listPort();  
  6.           
  7.         sp.selectPort(PORT_NAME);  
  8.         sp.write("210.36.16.166");  
  9.         sp.write("2");  
  10.         sp.startRead(120);  
  11.     }  

上面代码中的 PORT_NAME="COM2";


效果如下:

1.用 串口测试工具(附件中有) 打开COM3

这个是和COM2 连通的

如果在java程序中调用COM2,发送数据,那么COM3会收到,在COM3 中发送的数据,java可以监听到。


2.运行java的main程序:


COM3中收到了信息:


从COM3中得到数据:



0 0
原创粉丝点击