64位電腦通過串口發送數據到硬件

首先下載:RXTX的包,(僅64位有效)Rxtx開源包下載地址: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).

  1. package comme64;  
  2. import gnu.io.*;  
  3. import java.io.*;   
  4. import java.util.*;    
  5.    
  6.    
  7. public class SerialReader extends Observable implements Runnable,SerialPortEventListener  
  8.     {  
  9.     static CommPortIdentifier portId;  
  10.     int delayRead = 100;  
  11.     int numBytes; //   
  12.     private static byte[] readBuffer = new byte[1024]; //  
  13.     static Enumeration portList;  
  14.     InputStream inputStream;  
  15.     OutputStream outputStream;  
  16.     static SerialPort serialPort;  
  17.     HashMap serialParams;  
  18.     Thread readThread;  
  19.      
  20.     boolean isOpen = false;  
  21.      
  22.     public static final String PARAMS_DELAY = "delay read"; //   
  23.     public static final String PARAMS_TIMEOUT = "timeout"; // 超時時間  
  24.     public static final String PARAMS_PORT = "port name"; // 端口名稱  
  25.     public static final String PARAMS_DATABITS = "data bits"; //  
  26.     public static final String PARAMS_STOPBITS = "stop bits"; //  
  27.     public static final String PARAMS_PARITY = "parity"; // 奇偶校驗  
  28.     public static final String PARAMS_RATE = "rate"; //   
  29.   
  30.   
  31.     public boolean isOpen(){  
  32.     <span style="white-space:pre">  </span>return isOpen;  
  33.     }  
  34.     /**  
  35.      * 初始化端口操作的參數.  
  36.      * @throws SerialPortException   
  37.      *   
  38.      * @see  
  39.      */  
  40.     public SerialReader()  
  41.     {  
  42.     <span style="white-space:pre">  </span>isOpen = false;  
  43.     }  
  44.   
  45.   
  46.     public void open(HashMap params)  
  47.     {   
  48.     <span style="white-space:pre">  </span>serialParams = params;  
  49.     <span style="white-space:pre">  </span>if(isOpen){  
  50.     <span style="white-space:pre">      </span>close();  
  51.     <span style="white-space:pre">  </span>}  
  52.         try  
  53.         {  
  54.             // 參數初始  
  55.             int timeout = Integer.parseInt( serialParams.get( PARAMS_TIMEOUT )  
  56.                 .toString() );  
  57.             int rate = Integer.parseInt( serialParams.get( PARAMS_RATE )  
  58.                 .toString() );  
  59.             int dataBits = Integer.parseInt( serialParams.get( PARAMS_DATABITS )  
  60.                 .toString() );  
  61.             int stopBits = Integer.parseInt( serialParams.get( PARAMS_STOPBITS )  
  62.                 .toString() );  
  63.             int parity = Integer.parseInt( serialParams.get( PARAMS_PARITY )  
  64.                 .toString() );  
  65.             delayRead = Integer.parseInt( serialParams.get( PARAMS_DELAY )  
  66.                 .toString() );  
  67.             String port = serialParams.get( PARAMS_PORT ).toString();  
  68.             // 打開端口  
  69.             portId = CommPortIdentifier.getPortIdentifier( port );  
  70.             serialPort = ( SerialPort ) portId.open( "SerialReader", timeout );  
  71.             inputStream = serialPort.getInputStream();  
  72.             serialPort.addEventListener( this );  
  73.             serialPort.notifyOnDataAvailable( true );  
  74.             serialPort.setSerialPortParams( rate, dataBits, stopBits, parity );  
  75.             isOpen = true;  
  76.         }  
  77.         catch ( PortInUseException e )  
  78.         {  
  79.            // 端口"+serialParams.get( PARAMS_PORT ).toString()+"已經被佔�?;  
  80.         }  
  81.         catch ( TooManyListenersException e )  
  82.         {  
  83.            //"端口"+serialParams.get( PARAMS_PORT ).toString()+"監聽者過�?;  
  84.         }  
  85.         catch ( UnsupportedCommOperationException e )  
  86.         {  
  87.            //"端口操作命令不支�?;  
  88.         }  
  89.         catch ( NoSuchPortException e )  
  90.         {  
  91.           //"端口"+serialParams.get( PARAMS_PORT ).toString()+"不存�?;  
  92.         }  
  93.         catch ( IOException e )  
  94.         {  
  95.            //"打開端口"+serialParams.get( PARAMS_PORT ).toString()+"失敗";  
  96.         }  
  97.         serialParams.clear();  
  98.         Thread readThread = new Thread( this );  
  99.         readThread.start();  
  100.     }  
  101.   
  102.   
  103.        
  104.     public void run()  
  105.     {  
  106.         try  
  107.         {  
  108.             Thread.sleep(50);  
  109.         }  
  110.         catch ( InterruptedException e )  
  111.         {  
  112.         }  
  113.     }   
  114.     public void start(){  
  115.   try {    
  116.  outputStream = serialPort.getOutputStream();  
  117.     }   
  118.  catch (IOException e) {}  
  119.   try{   
  120.     readThread = new Thread(this);  
  121.     </span>readThread.start();  
  122.     </span>}   
  123.     </span>catch (Exception e) {  }  
  124.    }  //start() end  
  125.   
  126.   
  127.   
  128.   
  129.    public void run(String message) {  
  130.    try {   
  131.    Thread.sleep(4);   
  132.            }   
  133.    catch (InterruptedException e) {  }   
  134.  try {  
  135.  if(message!=null&&message.length()!=0)  
  136.     {   
  137.  System.out.println("run message:"+message);  
  138.          outputStream.write(message.getBytes());    
  139.  }  
  140. } catch (IOException e) {}  
  141.    }   
  142.       
  143.   
  144.   
  145.     public void close()   
  146.     {   
  147.         if (isOpen)  
  148.         {  
  149.             try  
  150.             {  
  151.             <span style="white-space:pre">  </span>serialPort.notifyOnDataAvailable(false);  
  152.             <span style="white-space:pre">  </span>serialPort.removeEventListener();  
  153.                 inputStream.close();  
  154.                 serialPort.close();  
  155.                 isOpen = false;  
  156.             } catch (IOException ex)  
  157.             {  
  158.             //"關閉串口失敗";  
  159.             }  
  160.         }  
  161.     }  
  162.       
  163.     public void serialEvent( SerialPortEvent event )  
  164.     {  
  165.         try  
  166.         {  
  167.             Thread.sleep( delayRead );  
  168.         }  
  169.         catch ( InterruptedException e )  
  170.         {  
  171.             e.printStackTrace();  
  172.         }  
  173.         switch ( event.getEventType() )  
  174.         {  
  175.             case SerialPortEvent.BI: // 10  
  176.             case SerialPortEvent.OE: // 7  
  177.             case SerialPortEvent.FE: // 9  
  178.             case SerialPortEvent.PE: // 8  
  179.             case SerialPortEvent.CD: // 6  
  180.             case SerialPortEvent.CTS: // 3  
  181.             case SerialPortEvent.DSR: // 4  
  182.             case SerialPortEvent.RI: // 5  
  183.             case SerialPortEvent.OUTPUT_BUFFER_EMPTY: // 2  
  184.                 break;  
  185.             case SerialPortEvent.DATA_AVAILABLE: // 1  
  186.                 try  
  187.                 {  
  188.                     // 多次讀取,將所有數據讀�?  
  189.                      while (inputStream.available() > 0) {  
  190.                      numBytes = inputStream.read(readBuffer);  
  191.                      }  
  192.                        
  193.                      //打印接收到的字節數據的ASCII�?  
  194.                      for(int i=0;i<numBytes;i++){  
  195.                     <span style="white-space:pre">  </span>// System.out.println("msg[" + numBytes + "]: [" +readBuffer[i] + "]:"+(char)readBuffer[i]);  
  196.                      }  
  197. //                    numBytes = inputStream.read( readBuffer );  
  198.                     changeMessage( readBuffer, numBytes );  
  199.                 }  
  200.                 catch ( IOException e )  
  201.                 {  
  202.                     e.printStackTrace();  
  203.                 }  
  204.                 break;  
  205.         }  
  206.     }  
  207.   
  208.   
  209.     // 通過observer pattern將收到的數據發�?給observer  
  210.     // 將buffer中的空字節刪除後再發送更新消�?通知觀察�?  
  211.     public void changeMessage( byte[] message, int length )  
  212.     {  
  213.         setChanged();  
  214.         byte[] temp = new byte[length];  
  215.         System.arraycopy( message, 0, temp, 0, length );  
  216.         notifyObservers( temp );  
  217.     }  
  218.   
  219.   
  220.     static void listPorts()  
  221.     {  
  222.         Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();  
  223.         while ( portEnum.hasMoreElements() )  
  224.         {  
  225.             CommPortIdentifier portIdentifier = ( CommPortIdentifier ) portEnum  
  226.                 .nextElement();  
  227.               
  228.         }  
  229.     }  
  230.       
  231.       
  232.     public void openSerialPort(String message)  
  233.     {  
  234.         HashMap<String, Comparable> params = new HashMap<String, Comparable>();    
  235.         String port="COM1";  
  236.         String rate = "9600";  
  237.         String dataBit = ""+SerialPort.DATABITS_8;  
  238.         String stopBit = ""+SerialPort.STOPBITS_1;  
  239.         String parity = ""+SerialPort.PARITY_NONE;      
  240.         int parityInt = SerialPort.PARITY_NONE;   
  241.         params.put( SerialReader.PARAMS_PORT, port ); // 端口名稱  
  242.         params.put( SerialReader.PARAMS_RATE, rate ); // 波特�?  
  243.         params.put( SerialReader.PARAMS_DATABITS,dataBit  ); // 數據�?  
  244.         params.put( SerialReader.PARAMS_STOPBITS, stopBit ); // 停止�?  
  245.         params.put( SerialReader.PARAMS_PARITY, parityInt ); // 無奇偶校�?  
  246.         params.put( SerialReader.PARAMS_TIMEOUT, 100 ); // 設備超時時間 1�?  
  247.         params.put( SerialReader.PARAMS_DELAY, 100 ); // 端口數據準備時間 1�?  
  248.         try {  
  249. open(params);//打開串口  
  250. //LoginFrame cf=new LoginFrame();  
  251. //addObserver(cf);  
  252. //也可以像上面�?��通過LoginFrame來綁定串口的通訊輸出.  
  253. if(message!=null&&message.length()!=0)  
  254.  {  
  255. String str="";  
  256. for(int i=0;i<10;i++)  
  257. {  
  258. str+=message;  
  259. }  
  260.  start();   
  261.     run(str);    
  262.  }   
  263. } catch (Exception e) {   
  264. }  
  265.     }  
  266.   
  267.   
  268.     static String getPortTypeName( int portType )  
  269.     {  
  270.         switch ( portType )  
  271.         {  
  272.             case CommPortIdentifier.PORT_I2C:  
  273.                 return "I2C";  
  274.             case CommPortIdentifier.PORT_PARALLEL:  
  275.                 return "Parallel";  
  276.             case CommPortIdentifier.PORT_RAW:  
  277.                 return "Raw";  
  278.             case CommPortIdentifier.PORT_RS485:  
  279.                 return "RS485";  
  280.             case CommPortIdentifier.PORT_SERIAL:  
  281.                 return "Serial";  
  282.             default:  
  283.                 return "unknown type";  
  284.         }  
  285.     }  
  286.   
  287.   
  288.        
  289.     public  HashSet<CommPortIdentifier> getAvailableSerialPorts()//本來static  
  290.     {  
  291.         HashSet<CommPortIdentifier> h = new HashSet<CommPortIdentifier>();  
  292.         Enumeration thePorts = CommPortIdentifier.getPortIdentifiers();  
  293.         while ( thePorts.hasMoreElements() )  
  294.         {  
  295.             CommPortIdentifier com = ( CommPortIdentifier ) thePorts  
  296.                 .nextElement();  
  297.             switch ( com.getPortType() )  
  298.             {  
  299.                 case CommPortIdentifier.PORT_SERIAL:  
  300.                     try  
  301.                     {  
  302.                         CommPort thePort = com.open( "CommUtil", 50 );  
  303.                         thePort.close();  
  304.                         h.add( com );  
  305.                     }  
  306.                     catch ( PortInUseException e )  
  307.                     {  
  308.                         System.out.println( "Port, " + com.getName()  
  309.                             + ", is in use." );  
  310.                     }  
  311.                     catch ( Exception e )  
  312.                     {  
  313.                         System.out.println( "Failed to open port "  
  314.                             + com.getName() + e );  
  315.                     }  
  316.             }  
  317.         }  
  318.         return h;  
  319.     }  
  320. }  
package comme64;
import gnu.io.*;
import java.io.*; 
import java.util.*;  
 
 
public class SerialReader extends Observable implements Runnable,SerialPortEventListener
    {
    static CommPortIdentifier portId;
    int delayRead = 100;
    int numBytes; // 
    private static byte[] readBuffer = new byte[1024]; //
    static Enumeration portList;
    InputStream inputStream;
    OutputStream outputStream;
    static SerialPort serialPort;
    HashMap serialParams;
    Thread readThread;
   
    boolean isOpen = false;
   
    public static final String PARAMS_DELAY = "delay read"; // 
    public static final String PARAMS_TIMEOUT = "timeout"; // 超時時間
    public static final String PARAMS_PORT = "port name"; // 端口名稱
    public static final String PARAMS_DATABITS = "data bits"; //
    public static final String PARAMS_STOPBITS = "stop bits"; //
    public static final String PARAMS_PARITY = "parity"; // 奇偶校驗
    public static final String PARAMS_RATE = "rate"; // 


    public boolean isOpen(){
    <span style="white-space:pre">	</span>return isOpen;
    }
    /**
     * 初始化端口操作的參數.
     * @throws SerialPortException 
     * 
     * @see
     */
    public SerialReader()
    {
    <span style="white-space:pre">	</span>isOpen = false;
    }


    public void open(HashMap params)
    { 
    <span style="white-space:pre">	</span>serialParams = params;
    <span style="white-space:pre">	</span>if(isOpen){
    <span style="white-space:pre">		</span>close();
    <span style="white-space:pre">	</span>}
        try
        {
            // 參數初始
            int timeout = Integer.parseInt( serialParams.get( PARAMS_TIMEOUT )
                .toString() );
            int rate = Integer.parseInt( serialParams.get( PARAMS_RATE )
                .toString() );
            int dataBits = Integer.parseInt( serialParams.get( PARAMS_DATABITS )
                .toString() );
            int stopBits = Integer.parseInt( serialParams.get( PARAMS_STOPBITS )
                .toString() );
            int parity = Integer.parseInt( serialParams.get( PARAMS_PARITY )
                .toString() );
            delayRead = Integer.parseInt( serialParams.get( PARAMS_DELAY )
                .toString() );
            String port = serialParams.get( PARAMS_PORT ).toString();
            // 打開端口
            portId = CommPortIdentifier.getPortIdentifier( port );
            serialPort = ( SerialPort ) portId.open( "SerialReader", timeout );
            inputStream = serialPort.getInputStream();
            serialPort.addEventListener( this );
            serialPort.notifyOnDataAvailable( true );
            serialPort.setSerialPortParams( rate, dataBits, stopBits, parity );
            isOpen = true;
        }
        catch ( PortInUseException e )
        {
           // 端口"+serialParams.get( PARAMS_PORT ).toString()+"已經被佔�?;
        }
        catch ( TooManyListenersException e )
        {
           //"端口"+serialParams.get( PARAMS_PORT ).toString()+"監聽者過�?;
        }
        catch ( UnsupportedCommOperationException e )
        {
           //"端口操作命令不支�?;
        }
        catch ( NoSuchPortException e )
        {
          //"端口"+serialParams.get( PARAMS_PORT ).toString()+"不存�?;
        }
        catch ( IOException e )
        {
           //"打開端口"+serialParams.get( PARAMS_PORT ).toString()+"失敗";
        }
        serialParams.clear();
        Thread readThread = new Thread( this );
        readThread.start();
    }


     
    public void run()
    {
        try
        {
            Thread.sleep(50);
        }
        catch ( InterruptedException e )
        {
        }
    } 
    public void start(){
  try {  
 outputStream = serialPort.getOutputStream();
    } 
 catch (IOException e) {}
  try{ 
    readThread = new Thread(this);
	</span>readThread.start();
	</span>} 
	</span>catch (Exception e) {  }
   }  //start() end




   public void run(String message) {
   try { 
   Thread.sleep(4); 
           } 
   catch (InterruptedException e) {  } 
 try {
 if(message!=null&&message.length()!=0)
    { 
 System.out.println("run message:"+message);
         outputStream.write(message.getBytes());  
 }
} catch (IOException e) {}
   } 
    


    public void close() 
    { 
        if (isOpen)
        {
            try
            {
            <span style="white-space:pre">	</span>serialPort.notifyOnDataAvailable(false);
            <span style="white-space:pre">	</span>serialPort.removeEventListener();
                inputStream.close();
                serialPort.close();
                isOpen = false;
            } catch (IOException ex)
            {
            //"關閉串口失敗";
            }
        }
    }
    
    public void serialEvent( SerialPortEvent event )
    {
        try
        {
            Thread.sleep( delayRead );
        }
        catch ( InterruptedException e )
        {
            e.printStackTrace();
        }
        switch ( event.getEventType() )
        {
            case SerialPortEvent.BI: // 10
            case SerialPortEvent.OE: // 7
            case SerialPortEvent.FE: // 9
            case SerialPortEvent.PE: // 8
            case SerialPortEvent.CD: // 6
            case SerialPortEvent.CTS: // 3
            case SerialPortEvent.DSR: // 4
            case SerialPortEvent.RI: // 5
            case SerialPortEvent.OUTPUT_BUFFER_EMPTY: // 2
                break;
            case SerialPortEvent.DATA_AVAILABLE: // 1
                try
                {
                    // 多次讀取,將所有數據讀�?
                     while (inputStream.available() > 0) {
                     numBytes = inputStream.read(readBuffer);
                     }
                     
                     //打印接收到的字節數據的ASCII�?
                     for(int i=0;i<numBytes;i++){
                    <span style="white-space:pre">	</span>// System.out.println("msg[" + numBytes + "]: [" +readBuffer[i] + "]:"+(char)readBuffer[i]);
                     }
//                    numBytes = inputStream.read( readBuffer );
                    changeMessage( readBuffer, numBytes );
                }
                catch ( IOException e )
                {
                    e.printStackTrace();
                }
                break;
        }
    }


    // 通過observer pattern將收到的數據發�?給observer
    // 將buffer中的空字節刪除後再發送更新消�?通知觀察�?
    public void changeMessage( byte[] message, int length )
    {
        setChanged();
        byte[] temp = new byte[length];
        System.arraycopy( message, 0, temp, 0, length );
        notifyObservers( temp );
    }


    static void listPorts()
    {
        Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();
        while ( portEnum.hasMoreElements() )
        {
            CommPortIdentifier portIdentifier = ( CommPortIdentifier ) portEnum
                .nextElement();
            
        }
    }
    
    
    public void openSerialPort(String message)
    {
        HashMap<String, Comparable> params = new HashMap<String, Comparable>();  
        String port="COM1";
        String rate = "9600";
        String dataBit = ""+SerialPort.DATABITS_8;
        String stopBit = ""+SerialPort.STOPBITS_1;
        String parity = ""+SerialPort.PARITY_NONE;    
        int parityInt = SerialPort.PARITY_NONE; 
        params.put( SerialReader.PARAMS_PORT, port ); // 端口名稱
        params.put( SerialReader.PARAMS_RATE, rate ); // 波特�?
        params.put( SerialReader.PARAMS_DATABITS,dataBit  ); // 數據�?
        params.put( SerialReader.PARAMS_STOPBITS, stopBit ); // 停止�?
        params.put( SerialReader.PARAMS_PARITY, parityInt ); // 無奇偶校�?
        params.put( SerialReader.PARAMS_TIMEOUT, 100 ); // 設備超時時間 1�?
        params.put( SerialReader.PARAMS_DELAY, 100 ); // 端口數據準備時間 1�?
        try {
open(params);//打開串口
//LoginFrame cf=new LoginFrame();
//addObserver(cf);
//也可以像上面�?��通過LoginFrame來綁定串口的通訊輸出.
if(message!=null&&message.length()!=0)
 {
String str="";
for(int i=0;i<10;i++)
{
str+=message;
}
 start(); 
    run(str);  
 } 
} catch (Exception e) { 
}
    }


    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  HashSet<CommPortIdentifier> getAvailableSerialPorts()//本來static
    {
        HashSet<CommPortIdentifier> h = new HashSet<CommPortIdentifier>();
        Enumeration thePorts = CommPortIdentifier.getPortIdentifiers();
        while ( thePorts.hasMoreElements() )
        {
            CommPortIdentifier com = ( CommPortIdentifier ) thePorts
                .nextElement();
            switch ( com.getPortType() )
            {
                case CommPortIdentifier.PORT_SERIAL:
                    try
                    {
                        CommPort thePort = com.open( "CommUtil", 50 );
                        thePort.close();
                        h.add( com );
                    }
                    catch ( PortInUseException e )
                    {
                        System.out.println( "Port, " + com.getName()
                            + ", is in use." );
                    }
                    catch ( Exception e )
                    {
                        System.out.println( "Failed to open port "
                            + com.getName() + e );
                    }
            }
        }
        return h;
    }
}
  1. <p>  
  2. </p><p></p>package comme64;</p> /*  
  3.   *數據位 8  
  4.  * 校驗位 0  
  5.  * 停止位 1  
  6.  * 波特率 115200  
  7.  * 端口com3  
  8.   */  
  9. import gnu.io.SerialPort;  
  10.   
  11.   
  12. import java.util.*;  
  13.   
  14.   
  15. public class Test implements Observer{   
  16. public static void main(String []args)  
  17. {  
  18. Test test = new Test();  
  19. test.send("串口數據發送至DTU轉發至服務器!");  
  20. while(true)  
  21. {  
  22. test.send("串口數據發送至DTU轉發至服務器!");  
  23. }  
  24. }  
  25. SerialReader sr=new SerialReader();   
  26. //    public Test()  
  27. //    {      
  28. //       openSerialPort("COM3"); //打開串口。  
  29. //    }   
  30.     public void update(Observable o, Object arg){      
  31.     String mt=new String((byte[])arg);    
  32.     System.out.println("---"+mt); //串口數據   
  33.     }   
  34.       
  35.     /**  
  36.      * 往串口發送數據,實現雙向通訊.  
  37.      * @param string message  
  38.      */  
  39.     public  void send(String message)  
  40.     {  
  41.     <span style="white-space:pre">  </span>Test test = new Test();  
  42.     <span style="white-space:pre">  </span>test.openSerialPort(message);  
  43.     }  
  44. <span style="white-space:pre">    </span>  
  45.     /**  
  46.      * 打開串口  
  47.      * @param String message  
  48.      */  
  49. <span style="white-space:pre">    </span>public void openSerialPort(String message)  
  50.     {   
  51.         HashMap<String, Comparable> params = new HashMap<String, Comparable>();    
  52.         String port="COM3";  
  53.         String rate = "115200";  
  54.         String dataBit = ""+SerialPort.DATABITS_8;  
  55.         String stopBit = ""+SerialPort.STOPBITS_1;  
  56.         String parity = ""+SerialPort.PARITY_NONE;      
  57.         int parityInt = SerialPort.PARITY_NONE;   
  58.         params.put( SerialReader.PARAMS_PORT, port ); // 端口名稱  
  59.         params.put( SerialReader.PARAMS_RATE, rate ); // 波特率  
  60.         params.put( SerialReader.PARAMS_DATABITS,dataBit  ); // 數據位  
  61.         params.put( SerialReader.PARAMS_STOPBITS, stopBit ); // 停止位  
  62.         params.put( SerialReader.PARAMS_PARITY, parityInt ); // 無奇偶校驗  
  63.         params.put( SerialReader.PARAMS_TIMEOUT,100 ); // 設備超時時間 1秒  
  64.         params.put( SerialReader.PARAMS_DELAY, 100 ); // 端口數據準備時間 1秒  
  65.         try {  
  66. sr.open(params);  
  67.    sr.addObserver(this);  
  68. if(message!=null&&message.length()!=0)  
  69.  {    
  70. sr.start();    
  71. sr.run(message);    
  72.  }   
  73. } catch (Exception e) {   
  74. }  
  75.     }  
  76.       
  77.   
  78.  public String Bytes2HexString(byte[] b) {   
  79.   String ret = "";   
  80.   for (int i = 0; i < b.length; i++) {   
  81.      String hex = Integer.toHexString(b[i] & 0xFF);   
  82.     if (hex.length() == 1) {   
  83.       hex = '0' + hex;   
  84.     }   
  85.    ret += hex.toUpperCase();   
  86.  }  
  87. return ret;  
  88.   }  
  89.   
  90.   
  91.  public  String hexString2binaryString(String hexString) {  
  92.  if (hexString == null || hexString.length() % 2 != 0)  
  93. return null;  
  94.  String bString = "", tmp;  
  95. for (int i = 0; i < hexString.length(); i++) {  
  96.  tmp = "0000" + Integer.toBinaryString(Integer.parseInt(hexString.substring(i, i + 1), 16));  
  97. bString += tmp.substring(tmp.length() - 4);  
  98.  }  
  99.  return bString;  
  100.  }   
  101. }   
<p>
</p><p></p>package comme64;</p> /*
  *數據位 8
 * 校驗位 0
 * 停止位 1
 * 波特率 115200
 * 端口com3
  */
import gnu.io.SerialPort;


import java.util.*;


public class Test implements Observer{ 
public static void main(String []args)
{
Test test = new Test();
test.send("串口數據發送至DTU轉發至服務器!");
while(true)
{
test.send("串口數據發送至DTU轉發至服務器!");
}
}
SerialReader sr=new SerialReader(); 
//    public Test()
//    {    
//       openSerialPort("COM3"); //打開串口。
//    } 
    public void update(Observable o, Object arg){    
    String mt=new String((byte[])arg);  
    System.out.println("---"+mt); //串口數據 
    } 
    
    /**
     * 往串口發送數據,實現雙向通訊.
     * @param string message
     */
    public  void send(String message)
    {
    <span style="white-space:pre">	</span>Test test = new Test();
    <span style="white-space:pre">	</span>test.openSerialPort(message);
    }
<span style="white-space:pre">	</span>
    /**
     * 打開串口
     * @param String message
     */
<span style="white-space:pre">	</span>public void openSerialPort(String message)
    { 
        HashMap<String, Comparable> params = new HashMap<String, Comparable>();  
        String port="COM3";
        String rate = "115200";
        String dataBit = ""+SerialPort.DATABITS_8;
        String stopBit = ""+SerialPort.STOPBITS_1;
        String parity = ""+SerialPort.PARITY_NONE;    
        int parityInt = SerialPort.PARITY_NONE; 
        params.put( SerialReader.PARAMS_PORT, port ); // 端口名稱
        params.put( SerialReader.PARAMS_RATE, rate ); // 波特率
        params.put( SerialReader.PARAMS_DATABITS,dataBit  ); // 數據位
        params.put( SerialReader.PARAMS_STOPBITS, stopBit ); // 停止位
        params.put( SerialReader.PARAMS_PARITY, parityInt ); // 無奇偶校驗
        params.put( SerialReader.PARAMS_TIMEOUT,100 ); // 設備超時時間 1秒
        params.put( SerialReader.PARAMS_DELAY, 100 ); // 端口數據準備時間 1秒
        try {
sr.open(params);
   sr.addObserver(this);
if(message!=null&&message.length()!=0)
 {  
sr.start();  
sr.run(message);  
 } 
} catch (Exception e) { 
}
    }
    

 public String Bytes2HexString(byte[] b) { 
  String ret = ""; 
  for (int i = 0; i < b.length; i++) { 
     String hex = Integer.toHexString(b[i] & 0xFF); 
    if (hex.length() == 1) { 
      hex = '0' + hex; 
    } 
   ret += hex.toUpperCase(); 
 }
return ret;
  }


 public  String hexString2binaryString(String hexString) {
 if (hexString == null || hexString.length() % 2 != 0)
return null;
 String bString = "", tmp;
for (int i = 0; i < hexString.length(); i++) {
 tmp = "0000" + Integer.toBinaryString(Integer.parseInt(hexString.substring(i, i + 1), 16));
bString += tmp.substring(tmp.length() - 4);
 }
 return bString;
 } 
} 

 通過Test.java的測試,可以成功把數據發送出去,這裏還是要注意端口的以及波特率的正確。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章