串口读取java中的写入

时间:2011-04-28 12:35:28

标签: java serial-port

我有一个应用程序,我需要将一些数据写入串口并从中获取响应。现在的顺序如下:

  1. 向串口发送消息。
  2. 等待回复
  3. 收到回复后,我必须处理该消息,直到那时应用程序才会发生任何事情。
  4. 我应该如何解决这个问题并解决它?我不擅长串口编程。我尝试了一个代码但是当我执行发送消息时我的应用程序停止了。可能是因为我在发送消息后正在阅读消息。我真的不知道要解决这个问题。我是否必须在应用程序启动期间开始收听端口?我必须保持端口开放吗?如果我每次需要打开端口都可以吗?以及如何使程序等待响应,直到从端口读取响应消息?请帮我解决这个问题..

    - 编辑 -

    package testConn;  
    import forms_helper.global_variables;  
    import java.io.IOException;  
    import java.io.InputStream;  
    import java.io.OutputStream;  
    import java.util.logging.Level;  
    import java.util.logging.Logger;  
    import javax.comm.*;  
    import java.util.*; 
    
    /** Check each port to see if it is open. **/  
    public class openPort implements SerialPortEventListener {
    
        static Enumeration portList;
        static CommPortIdentifier portId;
        static String messageString;
        public static SerialPort serialPort;
        static OutputStream outputStream;
        InputStream inputStream;
        static boolean outputBufferEmptyFlag = false;
    
        public void open() {
            Enumeration port_list = CommPortIdentifier.getPortIdentifiers();
    
            while (port_list.hasMoreElements()) {
                // Get the list of ports
                CommPortIdentifier port_id = (CommPortIdentifier) port_list.nextElement();
                if (port_id.getName().equals("/dev/ttyS1")) {
    
                    // Attempt to open it
                    try {
                        SerialPort port = (SerialPort) port_id.open("PortListOpen", 20);
                        System.out.println("Opened successfully");
                        try {
                            int baudRate = 9600; //
                            port.setSerialPortParams(
                                    baudRate,
                                    SerialPort.DATABITS_7,
                                    SerialPort.STOPBITS_1,
                                    SerialPort.PARITY_EVEN);
                            port.setDTR(true);
                           /*
    
                            port.setFlowControlMode(
                                    SerialPort.FLOWCONTROL_NONE);
                            *
                            */
                            System.out.println("properties are set");
                        } catch (UnsupportedCommOperationException e) {
                            System.out.println(e);
                        }
                        try {
                            //input = new SerialReader(in);
                            port.addEventListener(this);
                            System.out.println("listeners attached" + this);
                        } catch (TooManyListenersException e) {
                            System.out.println("too many listeners");
                        }
                        port.notifyOnDataAvailable(true);
                        //port.notifyOnOutputEmpty(true);
                        //sendMessage(port,"@PL");
                        //port.close ();
                        try {
                            inputStream = port.getInputStream();
                            System.out.println("inputstream" + inputStream.available());
                            outputStream = (OutputStream) port.getOutputStream();
    
                        } catch (IOException e) {
                            System.out.println(e);
                        }
    
                        //set the created variables to global variables
                        global_variables.port = port;
                        global_variables.inputStream = inputStream;
                        global_variables.outputStream = outputStream;
                    } catch (PortInUseException pe) {
                        System.out.println("Open failed");
                        String owner_name = port_id.getCurrentOwner();
                        if (owner_name == null) {
                            System.out.println("Port Owned by unidentified app");
                        } else // The owner name not returned correctly unless it is
                        // a Java program.
                        {
                            System.out.println("  " + owner_name);
                        }
                    }
                }
            }
        } 
    
        public static void sendMessage(SerialPort port, String msg) {
            if (port != null) {
                try {                
                    global_variables.outputStream.write(msg.getBytes());
                    global_variables.outputStream.flush();
                    try {
                        Thread.sleep(2000);  // Be sure data is xferred before closing
                        System.out.println("read called");
                        //SimpleRead read = new SimpleRead();
                        //int read = global_variables.inputStream.read();
                        //System.out.println("read call ended"+read);
                    } catch (Exception e) {
                    }
                } catch (IOException ex) {
                    Logger.getLogger(openPort.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    
        public void serialEvent(SerialPortEvent event) {
            System.out.println(event.getEventType());
            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:
                System.out.println("event.getEventType()");
                break;
                 *
                 */
    
                case SerialPortEvent.DATA_AVAILABLE:
                    System.out.println("inside event handler data available");
                    byte[] readBuffer = new byte[20];
                    try {
                        while (inputStream.available() > 0) {
                            int numBytes = inputStream.read(readBuffer);
                        }
                        System.out.print(new String(readBuffer));
                        System.exit(1);
                    } catch (IOException e) {
                        System.out.println(e);
                    }
    
                    break;
            }
        }
    }
    

    这段代码有什么问题?当我发送轮询消息时,我无法看到终端连接到serialport的响应。我在应用程序启动时打开连接,当我单击应用程序中的按钮时,我正在发送消息。我该如何解决这个问题?

2 个答案:

答案 0 :(得分:2)

请参阅this wikibook,事件驱动的串行通信部分。

答案 1 :(得分:2)

之前回答的问题,在这里:How do I get Java to use the serial port in Linux?

根据您的平台(如果您位于* NIX框中),您通常可以使用stty设置波特率/端口设置,然后只需打开/dev/tty*端口即可一个FileInputStream / FileOutputStream。我曾经有一大堆代码可以做到这一点而且运行得非常可靠,但是现在我去寻找它似乎错了。悲伤。

相关问题