2010년 5월 9일 일요일

[Java] Serial Communication API (시리얼통신)

아직까지도 주요 통신 수단인 시리얼 통신(RS-232C)은 현재 J2SE에서 제공하고 있지 않다.


하지만 하드웨어 관련한 프로젝트를 해보면 알겠지만 매우 필요한 수단이다.


일단은 표준 API가 아니므로 추가적으로 설치해야하는데 다음 링크를 따라가보자


[링크] : http://java.sun.com/products/javacomm/index.html

[파일] : 

 

* 설치


1. 링크를 따라가면 화면 좌측으로 다운로드 링크가 있다. 따라가도록 하자.

 

2. 아래쪽으로 플랫폼을 선택할 수 있는데 윈도우라면 Generic을 선택한 후 다운로드를 진행한다.

    (현재는 로그인을 해야 다운로드가진행된다. 메일주소와 이름등만 적으면 되므로 가입후 진행하자)

 

2. 첨부파일 저장 후 comm.jar, javax.comm.properties, win32com.dll 파일을 java.exe 파일이 있는 C:\Program Files\Java\jdk1.6.0_18\bin (경로는 본인에 맞게)에 복사한다.


3. comm.jar를 클래스 패스에 추가시킨다.


4. 사용하려는 클래스에서 import javax.comm.*; 을 하여 사용한다.

 

 


* 사용예제


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 = "Serial Comm.\n";
            out.write( msg.getBytes() );
            out.flush();
            out.close();
            port.close();
        }
        catch( Exception e ) {
            System.out.println( "Error:" + e.getMessage() );
        }
    }
}

댓글 없음:

댓글 쓰기