How to access the Serial port of a computer in Java?

Asked

Viewed 1,576 times

1

How do I access/control a Serial Port through Java? Currently I was able to access in C++, but in Java I don’t know how to do. Any suggestions?

1 answer

4


There is the jSSC library that provides communication with the serial port https://code.google.com/p/java-simple-serial-connector/

Add the dependency to your pom.xml, if you don’t use Maven download the library and put it in classpath.

<dependency>
    <groupId>org.scream3r</groupId>
    <artifactId>jssc</artifactId>
    <version>2.8.0</version>
</dependency>

Test Class

public class SerialTest {

public static void main(String[] args) {
    SerialPort serialPort = new SerialPort("COM1");

     try {
            System.out.println("Port opened: " + serialPort.openPort());
            System.out.println("Params setted: " + serialPort.setParams(9600, 8, 1, 0));
            System.out.println("\"Hello World!!!\" successfully writen to port: " + serialPort.writeBytes("Hello World!!!".getBytes()));
            System.out.println("Port closed: " + serialPort.closePort());
        }
        catch (SerialPortException ex){
            System.out.println(ex);
        }
}

}

exemplo

I took this example from the API website

  • Wouldn’t it be better to add a comment?

  • @Wellingtonavelino I set the example now

  • Ball show! @adelmo00

  • Very good this example @adelmo00, mutio thanks for the help!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.