Results 1 to 2 of 2
  1. #1
    Jasper is offline Member
    Join Date
    Apr 2012
    Posts
    3
    Rep Power
    0

    Default Serial communication using Threads

    Hello,

    i'm new to java serial programming and i'm using the RXTX API. I am able to send messages to hyperterminal or other serial devices by using a therad and receiving messages when using EventListeners. Now, i want to use a thread to handle my received messages, but there it goes wrong. I'm not able to display received messages, even worse my program crashes. Is there anyone who can help me?

    I followed the example from this website
    Below you find my code in written in Netbeans.
    Java Code:
    package org.Ardovlam.ESPA444;
    
    /**
     *
     * @author Jsnoeck
     */
    
    import gnu.io.CommPortIdentifier;
    import gnu.io.PortInUseException;
    import gnu.io.SerialPort;
    import gnu.io.UnsupportedCommOperationException;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.util.Calendar;
    import java.util.Date;
    import java.util.Enumeration;
    
    public class ESPAMaster extends javax.swing.JFrame {
    
    static CommPortIdentifier portId;
    static Enumeration portList; 
    static SerialPort serialPort;
    static OutputStream outputStream;
    private SerialParameters serialParameters;
    
    static InputStream inputStream;
    Calendar calendar;
        /**
         * Creates new form ESPAMaster
         */
        public ESPAMaster() {
            initComponents();
            portList = CommPortIdentifier.getPortIdentifiers();
            while (portList.hasMoreElements()) {
                portId = (CommPortIdentifier) portList.nextElement();
                if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                    jComboBoxCom.addItem(portId.getName());
                    
                }
            }
        }
    
        private void SendActionPerformed(java.awt.event.ActionEvent evt) {
            portList = CommPortIdentifier.getPortIdentifiers();
    
            while (portList.hasMoreElements()) {
                portId = (CommPortIdentifier) portList.nextElement();
                if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                    if (portId.getName().equals(jComboBoxCom.getSelectedItem())) {
                    //if (portId.getName().equals("/dev/term/a")) {
                        try {
                            serialPort = (SerialPort)
                                portId.open("ESPA444_socket", 2000);
                        } catch (PortInUseException e) {}
                        try {
                            outputStream = serialPort.getOutputStream();
                        } catch (IOException e) {}
                        //int iDataBits = (Integer) jComboBoxBits.getSelectedItem();
                        //Output.append("Can't open socket\n");
                        try {
                            serialPort.setSerialPortParams(getBaudRate(),
                                getDataBits(),
                                getStopBits(),
                                getParity());
                        } catch (UnsupportedCommOperationException e) {}
                        try {
                            outputStream.write(jTextField1.getText().getBytes());
                        } catch (IOException e) {}
                    }
                }
            }
            
        }
    
        private void ConnectActionPerformed(java.awt.event.ActionEvent evt) {
            DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            Date date = new Date();
            Output.append(dateFormat.format(date) + " : Trying to Connect\n"); 
            portList = CommPortIdentifier.getPortIdentifiers();
            
            while (portList.hasMoreElements()) {
                portId = (CommPortIdentifier) portList.nextElement();
                if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                    if (portId.getName().equals(jComboBoxCom.getSelectedItem())) {
                    //if (portId.getName().equals("/dev/term/a")) {
                        try {
                            serialPort = (SerialPort)
                                portId.open("ESPA444_Socket", 2000);
                                Output.append(dateFormat.format(date) + " : Connected to " + portId.getName() + "\n");
                        } catch (PortInUseException e) {
                                Output.append(dateFormat.format(date) + " : Port already in use\n");
                        }
                        try {
                            serialPort.setSerialPortParams(getBaudRate(),
                            getDataBits(),
                            getStopBits(),
                            getParity());
                            Output.append(dateFormat.format(date) + " : parameters => ");
                            Output.append("Baudrate : " + serialPort.getBaudRate() + ";");
                            Output.append("DataBits : " + serialPort.getDataBits() + ";");
                            Output.append("StopBits : " + serialPort.getStopBits() + ";");
                            Output.append("Parity : " + serialPort.getParity() + "\n");
                            //JOptionPane.showMessageDialog(null, "Connection OK!");
                            
                        } catch (UnsupportedCommOperationException e) {
                            Output.append("Portparameters wrong\n");
                        }
                        try {
                            inputStream = serialPort.getInputStream();
                            outputStream = serialPort.getOutputStream();
                        } catch (IOException e) {
                            Output.append("Input-Outputstream error\n");
                        }
    
                        (new Thread(new SerialReader(inputStream))).start();
                        (new Thread(new SerialWriter(outputStream))).start();
                        
                    }
                }
            }
        }
        public class SerialReader implements Runnable  {
           InputStream in;
                    
           public SerialReader ( InputStream in ) {        
                this.in = in;
           }
            
           public void run () {        
                byte[] buffer = new byte[1024];
                int len = -1;
                try { 
                    while (( len = this.in.read(buffer)) > -1 ) {                    
                                Output.append(new String(buffer,0,len) + "\n");
                            
                    }
                }
                catch ( IOException e ){}            
            }
        }
        public class SerialWriter implements Runnable {
            OutputStream out;
            
            public SerialWriter ( OutputStream out ) {
                this.out = out;
            }
            
            @Override
            public void run () {
                try {                
                    int c = 0;
                    while ( ( c = System.in.read()) > -1 ) {
                        this.out.write(c);
                    }                
                }
                catch ( IOException e ){}
            }
        }
        
        /**
         * @param args the command line arguments
         */
        public static void main(String args[]) {
             /*
             * Create and display the form
             */
           java.awt.EventQueue.invokeLater(new Runnable() {
    
                @Override
                public void run() {
                    new ESPAMaster().setVisible(true);
                }
            });
        }
            
    
        /**
         Gets Selected Baudrate
         @return Current Baudrate (int)
        */
        public int getBaudRate() {
            int i = 9600;
            if(jRadioButton1.isSelected()){
                i = 300;
            } else if (jRadioButton2.isSelected()){
                i = 1200;
            } else if (jRadioButton3.isSelected()){
                i = 2400;
            } else if (jRadioButton4.isSelected()){
                i = 4800;
            } else if (jRadioButton5.isSelected()){
                i = 9600;
            }
            return i;            
        }
        /**
         Gets Selected DataBits
         @return Current Databits (int)
        */
        public int getDataBits() {
            int i = SerialPort.DATABITS_8;
            if(jComboBoxBits.getSelectedItem().equals("7")) {
                i = SerialPort.DATABITS_7;
            }
            return i;
        }
        /**
         Gets Selected Parity
         @return Current Paruty (int)
        */
        public int getParity() {
            int i = SerialPort.PARITY_NONE;
            if(jComboBoxParity.getSelectedItem().equals("Even")) {
                i = SerialPort.PARITY_EVEN;
            } else if (jComboBoxParity.getSelectedItem().equals("Odd")) {
                i = SerialPort.PARITY_ODD;
            }
            return i;
        }
        /**
         Gets Selected StopBits
         @return Current StopBits (int)
        */    
        public int getStopBits() {
            int i = SerialPort.STOPBITS_1;
            if (jComboBoxStopbits.getSelectedItem().equals("1.5")) {
                i = SerialPort.STOPBITS_1_5;
            } else if (jComboBoxStopbits.getSelectedItem().equals("2")) {
                i = SerialPort.STOPBITS_2;
            }
            return i;
        }
        /**
         Gets Selected Handshake
         @return Current Handshake (int)
        */    
        public int getHandShake() {
            int i = SerialPort.FLOWCONTROL_NONE;
            if(jComboBoxHandshake.getSelectedIndex() == 1) {
                i = SerialPort.FLOWCONTROL_RTSCTS_IN;
            } else if (jComboBoxHandshake.getSelectedIndex() == 2) {
                i = SerialPort.FLOWCONTROL_RTSCTS_OUT;
            }        
            return i;
        }
    }
    Last edited by Jasper; 04-26-2012 at 10:34 PM.

  2. #2
    kjkrum's Avatar
    kjkrum is offline Senior Member
    Join Date
    Apr 2011
    Location
    Tucson, AZ
    Posts
    1,058
    Rep Power
    6

    Default Re: Serial communication using Threads

    That is a monstrous amount of code. Nobody's going to read all that to try to solve your problem. Can you boil it down to a SSCCE?

    Also, what do you mean you want to "use a thread" to handle your messages? You're using a thread any time your program is running.
    Get in the habit of using standard Java naming conventions!

Similar Threads

  1. Serial Communication
    By F.S. in forum Advanced Java
    Replies: 9
    Last Post: 03-06-2012, 07:07 AM
  2. Help with USB/Serial communication
    By Blackmore in forum Advanced Java
    Replies: 0
    Last Post: 08-16-2011, 08:45 PM
  3. Serial communication via ethernet-serial hub
    By Idiodyssey in forum New To Java
    Replies: 0
    Last Post: 05-04-2011, 02:23 PM
  4. Serial port Communication Problem
    By rjagan in forum New To Java
    Replies: 8
    Last Post: 04-20-2011, 12:36 PM
  5. Replies: 1
    Last Post: 07-30-2010, 08:29 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •