Java 与 Arduino uno 使用 RXTX串口通信

OS:win64位操作系统

rxtx:64位

下载地址:http://download.csdn.net/detail/h_hongchang/8428621

windows平台:
1、把rxtxParallel.dll、rxtxSerial.dll拷贝到:C:\WINDOWS\system32下。
2、如果是在开发的时候(JDK),需要把RXTXcomm.jar、rxtxParallel.dll、rxtxSerial.dll拷贝到..\jre...\lib\ext下;如:D:\Program Files\Java\jre1.6.0_02\lib\ext
3、而且需要把项目1.右键->2.Preperties(首选项)->3.Java Build Path->4.Libraries->5.展开RXTXcomm.jar->6.Native library location:(None)->7.浏览External Folder(选择至该项目的lib文件夹,如:E:/Item/MyItem/WebRoot/WEB-INF/lib).


  以下是java代码:

[java]  view plain  copy
  1. package com.rxtx.test;  
  2.   
  3. import gnu.io.CommPortIdentifier;  
  4. import gnu.io.PortInUseException;  
  5. import gnu.io.SerialPort;  
  6. import gnu.io.SerialPortEvent;  
  7. import gnu.io.SerialPortEventListener;  
  8. import gnu.io.UnsupportedCommOperationException;  
  9.   
  10. import java.io.BufferedInputStream;  
  11. import java.io.BufferedOutputStream;  
  12. import java.io.BufferedReader;  
  13. import java.io.BufferedWriter;  
  14. import java.io.IOException;  
  15. import java.io.InputStream;  
  16. import java.io.InputStreamReader;  
  17. import java.io.OutputStream;  
  18. import java.io.OutputStreamWriter;  
  19. import java.util.Enumeration;  
  20. import java.util.TooManyListenersException;  
  21.   
  22. /** 
  23.  * @项目名称 :串口监听 
  24.  * @文件名称 : 
  25.  * @所在包 : 
  26.  * @功能描述 : 
  27.  *    串口类 
  28.  * @创建者 :hhc 
  29.  * @创建日期 :2015.02.06 
  30.  * @修改记录 : 
  31.  */  
  32. public class SerialPortListener implements Runnable, SerialPortEventListener {  
  33.   
  34.     private String appName = "串口通讯";  
  35.     private int timeout = 2000;//open 端口时的等待时间  
  36.     private int threadTime = 0;  
  37.       
  38.     private CommPortIdentifier commPort;  
  39.     private SerialPort serialPort;  
  40.     private InputStream inputStream;  
  41.     private OutputStream outputStream;  
  42.       
  43.     /** 
  44.      * @方法名称 :listPort 
  45.      * @功能描述 :列出所有可用的串口 
  46.      * @返回值类型 :void 
  47.      */  
  48.     @SuppressWarnings("rawtypes")  
  49.     public void listPort(){  
  50.         CommPortIdentifier cpid;//当前串口对象  
  51.         Enumeration en = CommPortIdentifier.getPortIdentifiers();  
  52.         System.out.print("列出所有端口:");  
  53.         while(en.hasMoreElements()){  
  54.             cpid = (CommPortIdentifier)en.nextElement();  
  55.             //检测端口类型是否为串口  
  56.             if(cpid.getPortType() == CommPortIdentifier.PORT_SERIAL){  
  57.                 System.out.println(cpid.getName() + ", " + cpid.getCurrentOwner());  
  58.             }  
  59.         }  
  60.     }  
  61.       
  62.       
  63.     /** 
  64.      * @方法名称 :openPort 
  65.      * @功能描述 :选择一个端口,比如:COM1 并实例 SerialPort 
  66.      * @返回值类型 :void 
  67.      * @param portName 
  68.      */  
  69.     private void openPort(String portName){  
  70.         /* 打开该指定串口 */  
  71.         this.commPort = null;  
  72.         CommPortIdentifier cpid;  
  73.         Enumeration en = CommPortIdentifier.getPortIdentifiers();  
  74.   
  75.         while(en.hasMoreElements()){  
  76.             cpid = (CommPortIdentifier)en.nextElement();  
  77.             if(cpid.getPortType() == CommPortIdentifier.PORT_SERIAL && cpid.getName().equals(portName)){  
  78.                 this.commPort = cpid;  
  79.                 break;  
  80.             }  
  81.         }  
  82.         /* 实例 SerialPort*/  
  83.         if(commPort == null)  
  84.             log(String.format("无法找到名字为'%1$s'的串口!", portName));  
  85.         else{  
  86.             log("当前端口:"+commPort.getName());  
  87.             try{  
  88.                 //应用程序名【随意命名】,等待的毫秒数  
  89.                 serialPort = (SerialPort)commPort.open(appName, timeout);  
  90.             }catch(PortInUseException e){  
  91.                  // 端口已经被占用   
  92.                 throw new RuntimeException(String.format("端口'%1$s'正在使用中!",commPort.getName()));  
  93.             }  
  94.         }  
  95.     }  
  96.       
  97.     /** 
  98.      * @方法名称 :checkPort 
  99.      * @功能描述 :检查端口是否正确连接 
  100.      * @返回值类型 :void 
  101.      */  
  102.     private void checkPort(){  
  103.         if(commPort == null)  
  104.             throw new RuntimeException("没有选择端口,请使用 " +"selectPort(String portName) 方法选择端口");  
  105.           
  106.         if(serialPort == null){  
  107.             throw new RuntimeException("SerialPort 对象无效!");  
  108.         }  
  109.     }  
  110.       
  111.     /** 
  112.      * @方法名称 :write 
  113.      * @功能描述 :向端口发送数据,请在调用此方法前 先选择端口,并确定SerialPort正常打开! 
  114.      * @返回值类型 :void 
  115.      *    @param message 
  116.      * @throws IOException  
  117.      */  
  118.       
  119.     public void write(String message) throws InterruptedException {  
  120.         checkPort();  
  121.         try{  
  122.             outputStream = new BufferedOutputStream(serialPort.getOutputStream());  
  123.             outputStream.write(message.getBytes());  
  124.             log("消息:'"+message+"'发送成功!");  
  125.             outputStream.close();  
  126.         }catch(IOException e){  
  127.             throw new RuntimeException("向端口发送信息时出错:"+e.getMessage());  
  128.         }  
  129.           
  130.         /*另一种 
  131.          try { 
  132.             // 进行输入输出操作 
  133.             OutputStreamWriter writer = new OutputStreamWriter(serialPort.getOutputStream()); 
  134.             BufferedWriter bw = new BufferedWriter(writer); 
  135.             bw.write(message); 
  136.             bw.flush(); 
  137.             bw.close(); 
  138.             writer.close(); 
  139.             System.out.println("消息:'"+message+"'发送成功!"); 
  140.         } catch (IOException e) { 
  141.             throw new RuntimeException("向端口发送信息时出错:"+e.getMessage()); 
  142.         }*/  
  143.     }  
  144.       
  145.     /** 
  146.      * @方法名称 :startRead 
  147.      * @功能描述 :开始监听从端口中接收的数据 
  148.      * @返回值类型 :void 
  149.      *    @param time  监听程序时间,单位为秒,0 则是一直监听 
  150.      */  
  151.     public void startRead(int time){  
  152.         checkPort();  
  153.         try{  
  154.             inputStream = new BufferedInputStream(serialPort.getInputStream());  
  155.         }catch(IOException e){  
  156.             throw new RuntimeException("获取端口的InputStream出错:"+e.getMessage());  
  157.         }  
  158.           
  159.         try{  
  160.             serialPort.addEventListener(this);  
  161.             // 设置可监听   
  162.             serialPort.notifyOnDataAvailable(true);  
  163.             log(String.format("开始监听来自'%1$s'的数据--------------", commPort.getName()));  
  164.             serialPort.setSerialPortParams(9600,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);  
  165.         }catch(TooManyListenersException e){  
  166.              //端口监听者过多;    
  167.             throw new RuntimeException(e.getMessage());  
  168.         } catch (UnsupportedCommOperationException e) {  
  169.             //"端口操作命令不支持";    
  170.             e.printStackTrace();  
  171.         }  
  172.           
  173.           
  174.           
  175.           
  176.         /* 关闭监听 */  
  177.         if(time > 0){  
  178.             this.threadTime = time*1000;  
  179.             Thread t = new Thread(this);  
  180.             t.start();  
  181.             log(String.format("监听程序将在%1$d秒后关闭。。。。", time));  
  182.         }  
  183.     }  
  184.       
  185.       
  186.     /** 
  187.      * @方法名称 :close 
  188.      * @功能描述 :关闭 SerialPort 
  189.      * @返回值类型 :void 
  190.      */  
  191.     public void close(){  
  192.         serialPort.close();  
  193.         serialPort = null;  
  194.         commPort = null;  
  195.     }  
  196.       
  197.       
  198.     public void log(String msg){  
  199.         System.out.println(appName+" --> "+msg);  
  200.     }  
  201.   
  202.   
  203.     /** 
  204.      * 数据接收的监听处理函数 
  205.      */  
  206.     @Override  
  207.     public void serialEvent(SerialPortEvent arg0){  
  208.         switch(arg0.getEventType()){  
  209.         case SerialPortEvent.BI:/*Break interrupt,通讯中断*/   
  210.         case SerialPortEvent.OE:/*Overrun error,溢位错误*/   
  211.         case SerialPortEvent.FE:/*Framing error,传帧错误*/  
  212.         case SerialPortEvent.PE:/*Parity error,校验错误*/  
  213.         case SerialPortEvent.CD:/*Carrier detect,载波检测*/  
  214.         case SerialPortEvent.CTS:/*Clear to send,清除发送*/   
  215.         case SerialPortEvent.DSR:/*Data set ready,数据设备就绪*/   
  216.         case SerialPortEvent.RI:/*Ring indicator,响铃指示*/  
  217.         case SerialPortEvent.OUTPUT_BUFFER_EMPTY:/*Output buffer is empty,输出缓冲区清空*/   
  218.             break;  
  219.         case SerialPortEvent.DATA_AVAILABLE:/*Data available at the serial port,端口有可用数据。读到缓冲数组,输出到终端*/  
  220.             byte[] readBuffer = new byte[1024];  
  221.             String readStr="";  
  222.             String s2 = "";  
  223.             try {  
  224.                 while (inputStream.available() > 0) {  
  225.                     inputStream.read(readBuffer);  
  226.                     readStr += new String(readBuffer).trim();  
  227.                 }  
  228.                 log("接收到端口返回数据(长度为"+readStr.length()+"):"+readStr);  
  229.             } catch (IOException e) {  
  230.                 throw new RuntimeException(e.getMessage());  
  231.             }  
  232.               
  233.            /* 另一种// 进行输入输出操作 
  234.             BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); 
  235.             String line = null; 
  236.             try { 
  237.                 while ((line = reader.readLine()) != null) { 
  238.                     System.out.println(line); 
  239.                 } 
  240.                 reader.close(); 
  241.             } catch (IOException e) { 
  242.                 //e.printStackTrace(); 
  243.             }*/  
  244.         }  
  245.     }  
  246.   
  247.   
  248.     @Override  
  249.     public void run() {  
  250.         try{  
  251.             Thread.sleep(threadTime);  
  252.             serialPort.close();  
  253.             log(String.format("端口'%1$s'监听关闭了!", commPort.getName()));  
  254.         }catch(Exception e){  
  255.             e.printStackTrace();  
  256.         }  
  257.     }  
  258.       
  259.     /** 
  260.      * 测试 
  261.      * */  
  262.     public static void main(String[] args) throws InterruptedException {  
  263.             SerialPortListener sp = new SerialPortListener();  
  264.             /* 列出所有*/  
  265.             sp.listPort();  
  266.             /* 开打相应端口*/  
  267.             sp.openPort("COM4");  
  268.             /* 设置为一直监听*/  
  269.             sp.startRead(0);  
  270.             /* 首次连接后需暂停2秒再继续执行否则数据会有问题*/  
  271.             Thread.sleep(2000);  
  272.             sp.write("我");  
  273.             /* 之后发送信息前后间隔至少40ms,否则会将上条返返回信息合并为一条接收(视硬件情况调节)*/  
  274.             Thread.sleep(40);  
  275.             sp.write("你");  
  276.             Thread.sleep(5000);  
  277.             sp.write("我们");  
  278.     }  
  279. }  

以下是 arduino 代码:

[plain]  view plain  copy
  1. <span style="font-size:14px;">String comdata ="";//接收的字符串  
  2. void setup() {  
  3.     Serial.begin(9600);//串口波特率  
  4. }  
  5. void loop() {  
  6.     if(Serial.available() > 0){  
  7.         /* 接收字符串 */  
  8.         while (Serial.available() > 0)    
  9.         {  
  10.             comdata += char(Serial.read());  
  11.             delay(2);  
  12.         }  
  13.         if (comdata.length() > 0){  
  14.             if(comdata=="我"){  
  15.                 Serial.println("我什么我");  
  16.             }  
  17.             if(comdata=="你"){  
  18.                 Serial.println("你什么你");  
  19.             }  
  20.             if(comdata=="我们"){  
  21.                 Serial.println("我们什么我们");  
  22.             }  
  23.             comdata = "";  
  24.         }  
  25.           
  26.     }  
  27. }</span>  


运行后效果:


  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值