Posted on 2010-06-18 17:06 
云自无心水自闲 阅读(2401) 
评论(0)  编辑  收藏  所属分类: 
Java 、
心得体会 
			 
			
		 
		一、往串口写数据
import java.io.*;
import javax.comm.*;
import java.util.*;
public class PortWriter
{
    static Enumeration ports;
    static CommPortIdentifier pID;
    static OutputStream outStream;
    SerialPort serPort;
    static String messageToSend = "message!\n";
    
    public PortWriter() throws Exception{
        serPort = (SerialPort)pID.open("PortWriter",2000);
        outStream = serPort.getOutputStream();
        serPort.setSerialPortParams(9600, SerialPort.DATABITS_8,
        SerialPort.STOPBITS_1,
        SerialPort.PARITY_NONE);
    }    
    
    public static void main(String[] args) throws Exception{
        ports = CommPortIdentifier.getPortIdentifiers();
        
        while(ports.hasMoreElements())
        {
            pID = (CommPortIdentifier)ports.nextElement();
            System.out.println("Port " + pID.getName());
            
            if (pID.getPortType() == CommPortIdentifier.PORT_SERIAL)
            {
                if (pID.getName().equals("COM1"))
                {
                    PortWriter pWriter = new PortWriter();
                    System.out.println("COM1 found");
                }
            }
        }
        outStream.write(messageToSend.getBytes());
    }
}
二、通过串口传送文件:
import java.io.*;
import javax.comm.*;
public class PrintFile {
  public static void main(String args[]) throws Exception {
    if (args.length != 2) {
      System.err.println("usage : java PrintFile port file");
      System.err.println("sample: java PrintFile LPT1 sample.prn");
      System.exit(-1);
    }
    String portname = args[0];
    String filename = args[1];
    // Get port
    CommPortIdentifier portId = CommPortIdentifier
        .getPortIdentifier(portname);
    // Open port
    // Requires owner name and timeout
    CommPort port = portId.open("Java Printing", 30000);
    // Setup reading from file
    FileInputStream fis = new FileInputStream(filename);
    BufferedInputStream bis = new BufferedInputStream(fis);
    // Setup output
    OutputStream os = port.getOutputStream();
    BufferedOutputStream bos = new BufferedOutputStream(os);
    int c;
    while ((c = bis.read()) != -1) {
      bos.write(c);
    }
    // Close
    bos.close();
    bis.close();
    port.close();
  }
}
Below we have an example which sends a string to one serial port, receives it on the same port. You need a null-modem for this (just connect the RX and TX pins of your serial port to test this). In a production environment this example can be used as a template for sending and receiving data from e.g. a micro-controller board. 
 // derived from SUN's examples in the javax.comm package
// derived from SUN's examples in the javax.comm package
 import java.io.*;
import java.io.*;
 import java.util.*;
import java.util.*;
 //import javax.comm.*; // for SUN's serial/parallel port libraries
//import javax.comm.*; // for SUN's serial/parallel port libraries
 import gnu.io.*; // for rxtxSerial library
import gnu.io.*; // for rxtxSerial library


 public class nulltest implements Runnable, SerialPortEventListener
public class nulltest implements Runnable, SerialPortEventListener  {
{
 static CommPortIdentifier portId;
   static CommPortIdentifier portId;
 static CommPortIdentifier saveportId;
   static CommPortIdentifier saveportId;
 static Enumeration        portList;
   static Enumeration        portList;
 InputStream           inputStream;
   InputStream           inputStream;
 SerialPort           serialPort;
   SerialPort           serialPort;
 Thread           readThread;
   Thread           readThread;

 static String        messageString = "Hello, world!";
   static String        messageString = "Hello, world!";
 static OutputStream      outputStream;
   static OutputStream      outputStream;
 static boolean        outputBufferEmptyFlag = false;
   static boolean        outputBufferEmptyFlag = false;


 public static void main(String[] args)
   public static void main(String[] args)  {
{
 boolean           portFound = false;
      boolean           portFound = false;
 String           defaultPort;
      String           defaultPort;
 
      
 // determine the name of the serial port on several operating systems
      // determine the name of the serial port on several operating systems
 String osname = System.getProperty("os.name","").toLowerCase();
      String osname = System.getProperty("os.name","").toLowerCase();

 if ( osname.startsWith("windows") )
      if ( osname.startsWith("windows") )  {
{
 // windows
         // windows
 defaultPort = "COM1";
         defaultPort = "COM1";

 } else if (osname.startsWith("linux"))
      } else if (osname.startsWith("linux"))  {
{
 // linux
         // linux
 defaultPort = "/dev/ttyS0";
        defaultPort = "/dev/ttyS0";

 } else if ( osname.startsWith("mac") )
      } else if ( osname.startsWith("mac") )  {
{
 // mac
         // mac
 defaultPort = "????";
         defaultPort = "????";

 } else
      } else  {
{
 System.out.println("Sorry, your operating system is not supported");
         System.out.println("Sorry, your operating system is not supported");
 return;
         return;
 }
      }
 
          

 if (args.length > 0)
      if (args.length > 0)  {
{
 defaultPort = args[0];
         defaultPort = args[0];
 }
      } 

 System.out.println("Set default port to "+defaultPort);
      System.out.println("Set default port to "+defaultPort);
 
      
 // parse ports and if the default port is found, initialized the reader
        // parse ports and if the default port is found, initialized the reader
 portList = CommPortIdentifier.getPortIdentifiers();
      portList = CommPortIdentifier.getPortIdentifiers();

 while (portList.hasMoreElements())
      while (portList.hasMoreElements())  {
{
 portId = (CommPortIdentifier) portList.nextElement();
         portId = (CommPortIdentifier) portList.nextElement();

 if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL)
         if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL)  {
{

 if (portId.getName().equals(defaultPort))
            if (portId.getName().equals(defaultPort))  {
{
 System.out.println("Found port: "+defaultPort);
               System.out.println("Found port: "+defaultPort);
 portFound = true;
               portFound = true;
 // init reader thread
               // init reader thread
 nulltest reader = new nulltest();
               nulltest reader = new nulltest();
 }
            } 
 }
         } 
 
         
 }
      } 

 if (!portFound)
      if (!portFound)  {
{
 System.out.println("port " + defaultPort + " not found.");
         System.out.println("port " + defaultPort + " not found.");
 }
      } 
 
      
 }
   } 


 public void initwritetoport()
   public void initwritetoport()  {
{
 // initwritetoport() assumes that the port has already been opened and
      // initwritetoport() assumes that the port has already been opened and
 //    initialized by "public nulltest()"
      //    initialized by "public nulltest()"


 try
      try  {
{
 // get the outputstream
         // get the outputstream
 outputStream = serialPort.getOutputStream();
         outputStream = serialPort.getOutputStream();

 } catch (IOException e)
      } catch (IOException e)  {}
{}


 try
      try  {
{
 // activate the OUTPUT_BUFFER_EMPTY notifier
         // activate the OUTPUT_BUFFER_EMPTY notifier
 serialPort.notifyOnOutputEmpty(true);
         serialPort.notifyOnOutputEmpty(true);

 } catch (Exception e)
      } catch (Exception e)  {
{
 System.out.println("Error setting event notification");
         System.out.println("Error setting event notification");
 System.out.println(e.toString());
         System.out.println(e.toString());
 System.exit(-1);
         System.exit(-1);
 }
      }
 
      
 }
   }


 public void writetoport()
   public void writetoport()  {
{
 System.out.println("Writing \""+messageString+"\" to "+serialPort.getName());
      System.out.println("Writing \""+messageString+"\" to "+serialPort.getName());

 try
      try  {
{
 // write string to serial port
         // write string to serial port
 outputStream.write(messageString.getBytes());
         outputStream.write(messageString.getBytes());

 } catch (IOException e)
      } catch (IOException e)  {}
{}
 }
   }


 public nulltest()
   public nulltest()  {
{
 // initalize serial port
      // initalize serial port

 try
      try  {
{
 serialPort = (SerialPort) portId.open("SimpleReadApp", 2000);
         serialPort = (SerialPort) portId.open("SimpleReadApp", 2000);

 } catch (PortInUseException e)
      } catch (PortInUseException e)  {}
{}
 
   

 try
      try  {
{
 inputStream = serialPort.getInputStream();
         inputStream = serialPort.getInputStream();

 } catch (IOException e)
      } catch (IOException e)  {}
{}
 
   

 try
      try  {
{
 serialPort.addEventListener(this);
         serialPort.addEventListener(this);

 } catch (TooManyListenersException e)
      } catch (TooManyListenersException e)  {}
{}
 
      
 // activate the DATA_AVAILABLE notifier
      // activate the DATA_AVAILABLE notifier
 serialPort.notifyOnDataAvailable(true);
      serialPort.notifyOnDataAvailable(true);
 
   

 try
      try  {
{
 // set port parameters
         // set port parameters
 serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8,
         serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, 
 SerialPort.STOPBITS_1,
                     SerialPort.STOPBITS_1, 
 SerialPort.PARITY_NONE);
                     SerialPort.PARITY_NONE);

 } catch (UnsupportedCommOperationException e)
      } catch (UnsupportedCommOperationException e)  {}
{}
 
      
 // start the read thread
      // start the read thread
 readThread = new Thread(this);
      readThread = new Thread(this);
 readThread.start();
      readThread.start();
 
      
 }
   }


 public void run()
   public void run()  {
{
 // first thing in the thread, we initialize the write operation
      // first thing in the thread, we initialize the write operation
 initwritetoport();
      initwritetoport();

 try
      try  {
{

 while (true)
         while (true)  {
{
 // write string to port, the serialEvent will read it
            // write string to port, the serialEvent will read it
 writetoport();
            writetoport();
 Thread.sleep(1000);
            Thread.sleep(1000);
 }
         }

 } catch (InterruptedException e)
      } catch (InterruptedException e)  {}
{}
 }
   } 


 public void serialEvent(SerialPortEvent event)
   public void serialEvent(SerialPortEvent event)  {
{

 switch (event.getEventType())
      switch (event.getEventType())  {
{
 case SerialPortEvent.BI:
      case SerialPortEvent.BI:
 case SerialPortEvent.OE:
      case SerialPortEvent.OE:
 case SerialPortEvent.FE:
      case SerialPortEvent.FE:
 case SerialPortEvent.PE:
      case SerialPortEvent.PE:
 case SerialPortEvent.CD:
      case SerialPortEvent.CD:
 case SerialPortEvent.CTS:
      case SerialPortEvent.CTS:
 case SerialPortEvent.DSR:
      case SerialPortEvent.DSR:
 case SerialPortEvent.RI:
      case SerialPortEvent.RI:
 case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
      case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
 break;
         break;
 case SerialPortEvent.DATA_AVAILABLE:
      case SerialPortEvent.DATA_AVAILABLE:
 // we get here if data has been received
         // we get here if data has been received
 byte[] readBuffer = new byte[20];
         byte[] readBuffer = new byte[20];

 try
         try  {
{
 // read data
            // read data

 while (inputStream.available() > 0)
            while (inputStream.available() > 0)  {
{
 int numBytes = inputStream.read(readBuffer);
               int numBytes = inputStream.read(readBuffer);
 }
            } 
 // print data
            // print data
 String result  = new String(readBuffer);
            String result  = new String(readBuffer);
 System.out.println("Read: "+result);
            System.out.println("Read: "+result);

 } catch (IOException e)
         } catch (IOException e)  {}
{}
 
   
 break;
         break;
 }
      }
 }
   } 

 }
}

http://edn.embarcadero.com/article/31915
http://www.particle.kth.se/~lindsey/JavaCourse/Book/Part3/Chapter23/serialPortDemo.html
http://radio.javaranch.com/frank/2004/03/22/1079951422000.html
http://www.velocityreviews.com/forums/t144781-com-port-communication.html