Embedded Freaks..

August 8, 2008

How to open serial port (using rxtx)

Filed under: java — Tags: , , — kunilkuda @ 7:36 am

Ok. So here’s a brief explanation of how to open serial port in Java using rxtx.

First of all, you need to get the serial port’s ID

CommPortIdentifier portId =
  CommPortIdentifier.getPortIdentifier("/dev/ttyUSB0");

Then, you’ll need to ask the OS to give the serial port ownership to you.

SerialPort serialPort =
  (SerialPort) portId.open("Demo application", 5000);


The “Demo application” string is the application’s name. The rxtx will pass this value to OS as the application name who ask the serial port ownership (I think there’s some Unix command to view which application hold which system resource..I need to dig more on this use lsof /dev/<your serial device> to see which application that holds it. But I should remind you that “Demo application” string won’t come up using lsof or ps -ax).

The 5000 value is the timeout value that is given to the system to release the port (5000 ms = 5 seconds). If the current owner of the serial port doesn’t release the serial port within 5 seconds, rxtx will throw an IOException.

If you’re lucky (the current serial port owner willing to give the serial port to you, or nobody owns it currently), you can set the serial port parameters.

int baudRate = 57600; // 57600bps
try {
  // Set serial port to 57600bps-8N1..my favourite
  serialPort.setSerialPortParams(
    baudRate,
    SerialPort.DATABITS_8,
    SerialPort.STOPBITS_1,
    SerialPort.PARITY_NONE);
} catch (UnsupportedCommOperationException ex) {
  System.err.println(ex.getMessage());
}

Don’t forget to set its flow control

try {
  serialPort.setFlowControlMode(
        SerialPort.FLOWCONTROL_NONE);
  // OR
  // If CTS/RTS is needed
  //serialPort.setFlowControlMode(
  //      SerialPort.FLOWCONTROL_RTSCTS_IN | 
  //      SerialPort.FLOWCONTROL_RTSCTS_OUT);
} catch (UnsupportedCommOperationException ex) {
  System.err.println(ex.getMessage());
}

Lastly, before you can read or write to serial port. You’ll need its inputstream and outputstream.

OutputStream outStream = serialPort.getOutputStream();
InputStream inStream = serialPort.getInputStream();

So, here’s the complete example of the method to open the serial port

public class SerialPortHandler {
    private SerialPort serialPort;
    private OutputStream outStream;
    private InputStream inStream;

    public void connect(String portName) throws IOException {
        try {
            // Obtain a CommPortIdentifier object for the port you want to open
            CommPortIdentifier portId =
                    CommPortIdentifier.getPortIdentifier(portName);

            // Get the port's ownership
            serialPort =
                    (SerialPort) portId.open("Demo application", 5000);

            // Set the parameters of the connection.
            setSerialPortParameters();

            // Open the input and output streams for the connection. If they won't
            // open, close the port before throwing an exception.
            outStream = serialPort.getOutputStream();
            inStream = serialPort.getInputStream();
        } catch (NoSuchPortException e) {
            throw new IOException(e.getMessage());
        } catch (PortInUseException e) {
            throw new IOException(e.getMessage());
        } catch (IOException e) {
            serialPort.close();
            throw e;
        }
    }

    /**
     * Get the serial port input stream
     * @return The serial port input stream
     */
    public InputStream getSerialInputStream() {
        return inStream;
    }

    /**
     * Get the serial port output stream
     * @return The serial port output stream
     */
    public OutputStream getSerialOutputStream() {
        return outStream;
    }

    /**
     * Sets the serial port parameters
     */
    private void setSerialPortParameters() throws IOException {
        int baudRate = 57600; // 57600bps

        try {
            // Set serial port to 57600bps-8N1..my favourite
            serialPort.setSerialPortParams(
                    baudRate,
                    SerialPort.DATABITS_8,
                    SerialPort.STOPBITS_1,
                    SerialPort.PARITY_NONE);

            serialPort.setFlowControlMode(
                    SerialPort.FLOWCONTROL_NONE);
        } catch (UnsupportedCommOperationException ex) {
            throw new IOException("Unsupported serial port parameter");
        }
    }
}
About these ads

14 Comments »

  1. It helped me succedd in opening up my serial com project
    Thank you

    Comment by Narender — September 20, 2008 @ 12:52 pm

  2. You’re welcome.

    It’s a honour to me too to know my post worth something =)

    Comment by kunilkuda — September 20, 2008 @ 1:22 pm

  3. Thanks for tutorial. Is there a way (or any information) on how to set flow control as XON/XOFF?

    from hyperterm, it is only worked in xon-xoff mode, but when I set flowControl as XON|XOFF it did not seem to be worked.

    thanks.

    Comment by onculk — December 15, 2008 @ 7:41 pm

  4. Replace

    serialPort.setFlowControlMode(  
      SerialPort.FLOWCONTROL_RTSCTS_IN |  
      SerialPort.FLOWCONTROL_RTSCTS_OUT);
    

    with:

    serialPort.setFlowControlMode(  
      SerialPort.FLOWCONTROL_XONXOFF_IN |  
      SerialPort.FLOWCONTROL_XONXOFF_OUT);
    

    The XON/XOFF code (decoding/encoding) should be embedded inside the message that’s transmitted. Both rxtx and JavaComm don’t provide methods to parse it (ie. do it yourself in your program). Refer to Software flow control.

    Hyperterm works for both CTS/RTS and XON/XOFF, but not DTR/DSR. CTS/RTS and DTR/DSR are hardware based flow control. So both are mutually exclusive (choose one of it). XON/XOFF is software based flow control. It can be enabled while hardware based flow control is enabled (but it’ll be redundant to have both hardware and software flow control at the same time).

    Comment by kunilkuda — December 16, 2008 @ 1:07 pm

  5. Hi
    Problem:
    I had a h/w device connected to COMM4 port this devise will send some data after a hour but when i restart or start the computer the port will change to COMM1 so that COMM4 wont detected what is the problem to computer or a simple java program is here to detect the ports available in the system how can i enable the COMM4 and access the data if the computer restarted by java program or if COMM1 is only detected then change it to COMM4 by java

    i has a code to detect the ports
    package com;
    import java.io.IOException;
    import java.util.Enumeration;

    import gnu.io.*;
    public class GetPorts {
    static CommPortIdentifier portId;
    static Enumeration portList;
    public static void main(String[] args) {
    portList = CommPortIdentifier.getPortIdentifiers();

    while (portList.hasMoreElements()) {
    portId = (CommPortIdentifier) portList.nextElement();
    //if (portId.getPortType() == CommPortIdentifier.PORT_PARALLEL) {
    // if (portId.getName().equals(“COM1″)) {

    System.out.println(portId.getName()+” “+portId.getPortType()+portId.);
    //}
    //}
    }
    }

    }
    it shows all the enabled port in my system but can i change the port from comm1 to comm4 is this can be done pls help me thanks in advance

    Comment by Salish — August 3, 2009 @ 4:13 pm

  6. I don’t understand the question, but it seems like problem in OS configuration rather than Java (Windows I guess..because Linux never changes the hardware numbering, even though it’s USB).

    No..I don’t think you can change USB1 to USB4 within Java. It’s beyond Java’s reach, unless you use some kind of JNI to interface with Windows Control Panel. Here’s the link to fix the serial port mapping on your windows machine: https://www.patientecare.com/ser_port_doc/WinPorts.html (Check the remapping a serial port section).

    Try it on your own risk

    Comment by kunilkuda — August 5, 2009 @ 10:32 pm

  7. i’m running windows.

    when i do this:
    inStream = serialPort.getInputStream();

    i get nullpointerexception .. any tips ?

    Comment by Adix — March 13, 2010 @ 5:08 am

  8. Please sir,
    Regarding to hardware flow control FLOWCONTROL_RTSCTS_OUT, I understood that it uses 2 pins in the serial port to send control data, am I right?
    Should I be sure that the device that is connected to the serial port supports RTS/CRS? And HOW do I know that?
    Thank you

    Comment by smr — March 15, 2010 @ 11:44 pm

  9. Please sir,
    Regarding to flow control, how can I know that the device that is connected to the serial port supports RTS/CTS? RTSCTS are 2 pins in used for flow control data, am I right?

    Thank you

    Comment by smr — March 16, 2010 @ 12:17 am

  10. When I try to connect I get an error saying
    SEVERE: null
    java.io.IOException: Unknown Application

    what causes this?
    If it helps I use netbeans on a mac osx for development.
    Thanks in advance because your site is awesome.

    Comment by George Erickson — July 22, 2010 @ 12:22 am

  11. I am arun. I have a problem with one of my project. I have a loadcell from loadstar which is interfaced through USB.
    When I connect it to the ubuntu system, in /dev ttyUSB0 comes. But when I executed the code

    CommPortIdentifier portId = CommPortIdentifier.getPortIdentifier(“/dev/ttyUSB0″);

    it is showing the “NoSuchPortException” . Kindly help me to figure out the problem. I gave full permissions to /dev/ttyUSB0 file. But exception remains there.

    Comment by arunkumar v — March 2, 2011 @ 2:37 pm

  12. Hello Kunil,
    I have a serial x-y plotter for which I wrote a small java program to handle it. I send it a file (ascii) wich the right commands to draw a figure. It almost works, but after a while on plotting the file, it does erratic movements and drawings. It sure looks like flow control issues. I have tried all combinations of dip switches settings and cabling to no avail. The best result is produced when I set flowcontrol to xon xoff, (serialPort.setFlowControlMode(serialPort.FLOWCONTROL_XONXOFF_IN | serialPort.FLOWCONTROL_XONXOFF_OUT)
    But it still fails…sigh

    My question: do I have to provide a function to read when the plotter sends the XOFF character? Or that is already taken care by the API in a transparent way for the developer?

    Thank you very much, and best regards,
    Andres

    Comment by Andres — February 2, 2012 @ 1:34 pm

  13. Its very useful very nice tutorial thank u soooo much

    Comment by ash — April 15, 2012 @ 6:10 pm


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

The Silver is the New Black Theme. Blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: