`
xitongyunwei
  • 浏览: 926260 次
文章分类
社区版块
存档分类
最新评论

Linux Java 串口通信

 
阅读更多

费了好大的劲搞定Linux系统上用Java写串口通信的问题。

jdk中没有原生的串口api,网上找了半天的资料,大概知道了:Linux系统上用Java写串口程序,有两个包比较常用,一个是当年sun官方出的javacomm,但是找了半天都是老版本的居多,oracle官方不提供下载了,不爽。另一个是gnu的rxtx comm,看了一下还算靠谱,不过官方的wiki上(http://rxtx.qbang.org/wiki/index.php/Main_Page)说linux版本的在卸载usb转串口线的时候会崩溃,顿时心头一颤。下载下来之后试了一下,确实可以用,系统里几个原生的串口都识别了,但唯独我的Arduino板子不识别。

捉急之时想到了Arduino IDE里面是有Serial Monitor的,而且也是用Java写的,于是去Arduino的安装目录里面找找,果然发现了在arduino安装目录下的lib目录下,有RXTXcomm.jar、librxtxSerial.so、librxtxSerial64.so这三个文件(我的Linux是64位的,不知道32位的是不是没有64.so这个文件),可以去Arduino官网上下载一个IDE,把这几个文件复制出来,按照rxtx wiki上说明使用,用法是一样的。

如果也是用的64位的系统,可以从这里下载:http://download.csdn.net/detail/bhq2010/5141550

如果要脱离eclipse单独执行串口通信程序,将RXTXcomm.jar文件复制到$JAVA_HOME/jre/lib/ext目录下,将librxtxSerial.so和librxtxSerial64.so复制到$JAVA_HOME/jre/lib/amd64/目录下(如果是32位系统应该是i386或者i686,而不是amd64)就OK了,官方wiki上描述的安装步骤很麻烦,做了一下不行。

下面是一个例程,是官方的wiki里例程的改进版【PS:以下代码在win7上用不了,不能用BufferedReader包装InputStream,不知道为啥,有知道原因的童鞋请告诉我】:

package test;
import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

public class TwoWaySerialComm
{
    public TwoWaySerialComm()
    {
        super();
    }
    
    void connect ( String portName ) throws Exception
    {
        CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
        if ( portIdentifier.isCurrentlyOwned() )
        {
            System.out.println("Error: Port is currently in use");
        }
        else
        {
            CommPort commPort = portIdentifier.open(this.getClass().getName(),2000);
            
            if ( commPort instanceof SerialPort )
            {
                SerialPort serialPort = (SerialPort) commPort;
                serialPort.setSerialPortParams(9600,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
                
                InputStream in = serialPort.getInputStream();
                
                InputStreamReader reader = new InputStreamReader(in);
                BufferedReader r = new BufferedReader(reader);
                
                (new Thread(new SerialReader(r))).start();

            }
            else
            {
                System.out.println("Error: Only serial ports are handled by this example.");
            }
        }     
    }
    
    /** */
    public static class SerialReader implements Runnable 
    {
        BufferedReader in;
        
        public SerialReader ( BufferedReader in )
        {
            this.in = in;
        }
        
        public void run ()
        {
            try
            {
                String line;
            	while ((line = in.readLine()) != null){
                	System.out.println(line);
                }
            }
            catch ( IOException e )
            {
                e.printStackTrace();
            }            
        }
    }

    /** */
    public static class SerialWriter implements Runnable 
    {
        OutputStream out;
        
        public SerialWriter ( OutputStream out )
        {
            this.out = out;
        }
        
        public void run ()
        {
            try
            {                
                int c = 0;
                while ( ( c = System.in.read()) > -1 )
                {
                    this.out.write(c);
                }                
            }
            catch ( IOException e )
            {
                e.printStackTrace();
            }            
        }
    }
    
    static void listPorts()
    {
        @SuppressWarnings("unchecked")
		java.util.Enumeration<CommPortIdentifier> portEnum = CommPortIdentifier.getPortIdentifiers();
        while ( portEnum.hasMoreElements() ) 
        {
            CommPortIdentifier portIdentifier = portEnum.nextElement();
            System.out.println(portIdentifier.getName()  +  " - " +  getPortTypeName(portIdentifier.getPortType()) );
        }        
    }
    
    static String getPortTypeName ( int portType )
    {
        switch ( portType )
        {
            case CommPortIdentifier.PORT_I2C:
                return "I2C";
            case CommPortIdentifier.PORT_PARALLEL:
                return "Parallel";
            case CommPortIdentifier.PORT_RAW:
                return "Raw";
            case CommPortIdentifier.PORT_RS485:
                return "RS485";
            case CommPortIdentifier.PORT_SERIAL:
                return "Serial";
            default:
                return "unknown type";
        }
    }
    
    public static void main ( String[] args )
    {
    	listPorts();
        try
        {
            (new TwoWaySerialComm()).connect("/dev/ttyACM0");
        }
        catch ( Exception e )
        {
            e.printStackTrace();
        }
    }
}


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics