<rt id="bn8ez"></rt>
<label id="bn8ez"></label>

  • <span id="bn8ez"></span>

    <label id="bn8ez"><meter id="bn8ez"></meter></label>

    云自無心水自閑

    天平山上白云泉,云自無心水自閑。何必奔沖山下去,更添波浪向人間!
    posts - 288, comments - 524, trackbacks - 0, articles - 6
      BlogJava :: 首頁 :: 新隨筆 :: 聯(lián)系 :: 聚合  :: 管理

    java comm操作串口

    Posted on 2010-06-18 17:06 云自無心水自閑 閱讀(2391) 評論(0)  編輯  收藏 所屬分類: Java心得體會
    一、往串口寫數(shù)據(jù)
    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[] argsthrows 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
    import java.io.*;
    import java.util.*;
    //import javax.comm.*; // for SUN's serial/parallel port libraries
    import gnu.io.*// for rxtxSerial library

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

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

       
    public static void main(String[] args) {
          
    boolean           portFound = false;
          String           defaultPort;
          
          
    // determine the name of the serial port on several operating systems
          String osname = System.getProperty("os.name","").toLowerCase();
          
    if ( osname.startsWith("windows") ) {
             
    // windows
             defaultPort = "COM1";
          }
     else if (osname.startsWith("linux")) {
             
    // linux
            defaultPort = "/dev/ttyS0";
          }
     else if ( osname.startsWith("mac") ) {
             
    // mac
             defaultPort = "????";
          }
     else {
             System.out.println(
    "Sorry, your operating system is not supported");
             
    return;
          }

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

          System.out.println(
    "Set default port to "+defaultPort);
          
            
    // parse ports and if the default port is found, initialized the reader
          portList = CommPortIdentifier.getPortIdentifiers();
          
    while (portList.hasMoreElements()) {
             portId 
    = (CommPortIdentifier) portList.nextElement();
             
    if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                
    if (portId.getName().equals(defaultPort)) {
                   System.out.println(
    "Found port: "+defaultPort);
                   portFound 
    = true;
                   
    // init reader thread
                   nulltest reader = new nulltest();
                }
     
             }
     
             
          }
     
          
    if (!portFound) {
             System.out.println(
    "port " + defaultPort + " not found.");
          }
     
          
       }
     

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

          
    try {
             
    // get the outputstream
             outputStream = serialPort.getOutputStream();
          }
     catch (IOException e) {}

          
    try {
             
    // activate the OUTPUT_BUFFER_EMPTY notifier
             serialPort.notifyOnOutputEmpty(true);
          }
     catch (Exception e) {
             System.out.println(
    "Error setting event notification");
             System.out.println(e.toString());
             System.exit(
    -1);
          }

          
       }


       
    public void writetoport() {
          System.out.println(
    "Writing \""+messageString+"\" to "+serialPort.getName());
          
    try {
             
    // write string to serial port
             outputStream.write(messageString.getBytes());
          }
     catch (IOException e) {}
       }


       
    public nulltest() {
          
    // initalize serial port
          try {
             serialPort 
    = (SerialPort) portId.open("SimpleReadApp"2000);
          }
     catch (PortInUseException e) {}
       
          
    try {
             inputStream 
    = serialPort.getInputStream();
          }
     catch (IOException e) {}
       
          
    try {
             serialPort.addEventListener(
    this);
          }
     catch (TooManyListenersException e) {}
          
          
    // activate the DATA_AVAILABLE notifier
          serialPort.notifyOnDataAvailable(true);
       
          
    try {
             
    // set port parameters
             serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, 
                         SerialPort.STOPBITS_1, 
                         SerialPort.PARITY_NONE);
          }
     catch (UnsupportedCommOperationException e) {}
          
          
    // start the read thread
          readThread = new Thread(this);
          readThread.start();
          
       }


       
    public void run() {
          
    // first thing in the thread, we initialize the write operation
          initwritetoport();
          
    try {
             
    while (true{
                
    // write string to port, the serialEvent will read it
                writetoport();
                Thread.sleep(
    1000);
             }

          }
     catch (InterruptedException e) {}
       }
     

       
    public void serialEvent(SerialPortEvent event) {
          
    switch (event.getEventType()) {
          
    case SerialPortEvent.BI:
          
    case SerialPortEvent.OE:
          
    case SerialPortEvent.FE:
          
    case SerialPortEvent.PE:
          
    case SerialPortEvent.CD:
          
    case SerialPortEvent.CTS:
          
    case SerialPortEvent.DSR:
          
    case SerialPortEvent.RI:
          
    case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
             
    break;
          
    case SerialPortEvent.DATA_AVAILABLE:
             
    // we get here if data has been received
             byte[] readBuffer = new byte[20];
             
    try {
                
    // read data
                while (inputStream.available() > 0{
                   
    int numBytes = inputStream.read(readBuffer);
                }
     
                
    // print data
                String result  = new String(readBuffer);
                System.out.println(
    "Read: "+result);
             }
     catch (IOException e) {}
       
             
    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


    主站蜘蛛池模板: 狠狠亚洲婷婷综合色香五月排名| 国产四虎免费精品视频| 国产午夜免费福利红片| 亚洲精品成a人在线观看☆| 亚洲三级高清免费| 自拍日韩亚洲一区在线| 免费AA片少妇人AA片直播| 亚洲av午夜精品无码专区| www.999精品视频观看免费| 亚洲天堂一区在线| 成年女人毛片免费观看97| 亚洲中文字幕久久精品无码VA| 毛色毛片免费观看| 亚洲AV无码专区在线观看成人| 全黄a免费一级毛片人人爱| 免费人成动漫在线播放r18 | 久久久久免费看黄A片APP| 亚洲伊人久久大香线蕉结合| 麻豆精品国产免费观看| 亚洲jizzjizz少妇| 日本黄页网站免费| 国产精品午夜免费观看网站| 亚洲AV综合色一区二区三区| 在线成人爽a毛片免费软件| 亚洲av乱码一区二区三区香蕉| 成年女人永久免费观看片| 国产精品免费久久久久影院| 久久精品亚洲综合| 毛片基地免费视频a| 特黄aa级毛片免费视频播放| 亚洲精品无码久久久久去q| 免费看又黄又无码的网站| 亚洲一区二区三区丝袜| 亚洲片国产一区一级在线观看| 国产成人精品无码免费看 | 在线观看国产情趣免费视频| 午夜肉伦伦影院久久精品免费看国产一区二区三区 | 亚洲日本一区二区| 暖暖免费高清日本中文| 国产自国产自愉自愉免费24区| 亚洲综合网美国十次|