[Java/Gradle] RS232 통신 (java 11 or higher)

Programming/Java 2021. 12. 4. 13:09 Posted by 생각하는로뎅
반응형

Java RS232 통신을 하려면. 통신 라이브러리가 필요하다.

 

찾아본 라이브러리는 2가지이다.

 

1. rxtx (https://github.com/rxtx/rxtx)

2. jSerialComm (https://fazecast.github.io/jSerialComm/)

 

 

제일 처음 접한 rxtx 라이브러리는 java 8 에서만 동작했다.

 

필자는 java 11 이상에서 사용해야한다는 조건이 있었기 때문에, 인터넷을 이잡듯이 찾아보았지만 결국 실패하고 다른 라이브러리를 찾아보기로 했다.

 

java 11 이상에서 사용하면 아래와 같은 오류가 발생한다.

#
# A fatal error has been detected by the Java Runtime Environment:
#
#  EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x0000000180005b00, pid=31240, tid=8888
#
# JRE version: Java(TM) SE Runtime Environment 18.9 (11.0.9+7) (build 11.0.9+7-LTS)
# Java VM: Java HotSpot(TM) 64-Bit Server VM 18.9 (11.0.9+7-LTS, mixed mode, tiered, compressed oops, g1 gc, windows-amd64)
# Problematic frame:
# C  [rxtxSerial.dll+0x5b00]
#
# No core dump will be written. Minidumps are not enabled by default on client versions of Windows
#
# An error report file with more information is saved as:
# C:\Users\posk1\IdeaProjects\koiskbodycheck\hs_err_pid31240.log
#
# If you would like to submit a bug report, please visit:
#   https://bugreport.java.com/bugreport/crash.jsp
# The crash happened outside the Java Virtual Machine in native code.
# See problematic frame for where to report the bug.
#

 

rxtx 라이브러리가 윈도우 비트에 맞게 dll 을 jdk bin 폴더에 넣어줘야하는 번거롭기도했다.

 

 

다음 찾은 라이브러리는 jSerialComm 라이브러리인데, 윈도우 비트에 맞게 셋팅해줄 필요도 없고, 더군다나 java 11 이상에서 작동이 되었다.

 

 

1. Gradle 을 아래와 같이 추가한다.

dependencies {

    // https://mvnrepository.com/artifact/com.fazecast/jSerialComm
    implementation group: 'com.fazecast', name: 'jSerialComm', version: '1.3.10'

}

 

2. 아래 소스 코드를 추가해서 실행해 본다.

 try {

    // COM6 포트를 가져온다.
    SerialPort serialPort = SerialPort.getCommPort("COM6");

    // 시리얼 포트를 오픈한다.
    boolean isOpen = serialPort.openPort();

    if (isOpen) {

        // 입력을 받기 위해 InputStream을 가져온다.
        InputStream in = serialPort.getInputStream();

        byte[] buffer = new byte[1024];
        int len = -1;
        while ((len = in.read(buffer)) > -1) {
            // 들어오는 입력 값을 출력한다.
            System.out.print(new String(buffer, 0, len));
        }

    }

 } catch (Exception e) {
      e.printStackTrace();
}

 

 

 

 

 

반응형