본문 바로가기

프로그램

[Java 응용] 자바 시리얼통신(RS-232c) 소스

[Java 응용] 자바 시리얼통신(RS-232c) 소스


준비물:

자바에서 RS-232c나 패러럴(parallel)포트에 접근하기 위해서는 Communication API을 사용해야 합니다.

Communication API은 자바 J2SE에서 제공하는 표준 API가 아니므로, 추가적으로 다운로드 받아서 설치 해주셔야 합니다.

 

참고로, 자바의 Communication API 공식 사이트 주소는 다음과 같습니다.

http://java.sun.com/products/javacomm/index.html

 

순서:

1. http://java.sun.com/products/javacomm/downloads/index.html

접속하여 해당 OS별 API을 다운로드 받습니다. 윈도우즈의 경우, (javacomm20-win32.zip) 입니다.

 

2. 압축을 푼후, comm.jar, javax.comm.properties, win32com.dll 파일을

자바설치디렉터리\bin 폴더(java.exe 파일이 존재하는 폴더) 복사에 넣습니다.

 

3. 그리고,comm.jar을 클래스 패스에 추가 시켜 줍니다.

 

4. 이제, Communication API을 사용하려는 클래스에서  javax.comm 팩키지를 import해주면 됩니다.

ex) import javax.comm.*;

 


 

첨부파일: Rs232c.java

 

//Rs232c.java

import java.io.*;
import javax.comm.*;
public class Rs232c {
    public static void main( String arg[] ) {
        try {
            CommPortIdentifier ports = CommPortIdentifier.getPortIdentifier( "COM1" );
            SerialPort port = ( SerialPort )ports.open( "RS232C", 1000 );
            port.setSerialPortParams( 9600,
                SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE );
            port.setFlowControlMode( SerialPort.FLOWCONTROL_NONE );
            OutputStream out = port.getOutputStream();
            String msg = "Hello";
            out.write( msg.getBytes() );
            out.flush();
            out.close();
            port.close();
        }
        catch( Exception e ) {
            System.out.println( "Error:" + e.getMessage() );
        }
    }
}