이번 시간은 rxtx홈페이지에 있는 예제를 간단한 설명과 함께 알아보도록 하겠습니다.


예제는 아래의 링크에 연결 되어 있습니다.

http://rxtx.qbang.org/wiki/index.php/Two_way_communcation_with_the_serial_port


예제 소스에 내용은 이렇습니다.


1. 시리얼 포트를 접속

2. 입력 스트림 얻기

3. 출력 스트림 얻기

4. 2번에서 취득한 입력 스트림을 SerialReader클래스로 넘겨

    독립된 쓰레드에서 입력스트림으로 들어온 데이터를 읽는다. 

5.3번에서 취득한 출력 스트림을 SerialWriter클래스로 넘겨

    독립된 쓰레드에서 키보드 입력을 받아 출력 스트림에 쓰기를 한다.


소스 내용을 글로 쓰니 좀 어색하네요. ^^;


제쪽에서 쪼금 아주 쪼금 커멘트를 넣은 소스입니다.


[샘플 소스] 

import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class TwoWaySerialComm {
	public TwoWaySerialComm() {
		super();
	}

	private void connect(String portName) throws Exception {

		
		System.out.printf("Port : %s\n", portName);
		
		CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);

		if (portIdentifier.isCurrentlyOwned()) {
			System.out.println("Error: Port is currently in use");
		} else {
			CommPort commPort = portIdentifier.open(this.getClass().getName(),
					2000);

			if (commPort instanceof SerialPort) {
				SerialPort serialPort = (SerialPort) commPort;
				serialPort.setSerialPortParams(57600,	// 통신속도
						SerialPort.DATABITS_8, 			// 데이터 비트
						SerialPort.STOPBITS_1,			// stop 비트
						SerialPort.PARITY_NONE);		// 패리티

				// 입력 스트림
				InputStream in = serialPort.getInputStream();
				
				// 출력 스트림
				OutputStream out = serialPort.getOutputStream();

				(new Thread(new SerialReader(in))).start();
				(new Thread(new SerialWriter(out))).start();

			} else {
				System.out
						.println("Error: Only serial ports are handled by this example.");
			}
		}
	}

	/**
	 * 시리얼 읽기
	 */
	public static class SerialReader implements Runnable {
		InputStream in;

		public SerialReader(InputStream in) {
			this.in = in;
		}

		public void run() {
			byte[] buffer = new byte[1024];
			int len = -1;
			
			try {
				while ((len = this.in.read(buffer)) > -1) {
					System.out.print(new String(buffer, 0, len));
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/** 
	 * 시리얼에 쓰기 
	 */
	public static class SerialWriter implements Runnable {
		OutputStream out;

		public SerialWriter(OutputStream out) {
			this.out = out;
		}

		public void run() {
			try {
				int c = 0;
				
				System.out.println("\nKeyborad Input Read!!!!");
				while ((c = System.in.read()) > -1) {
					this.out.write(c);
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public static void main(String[] args) {
		try {
			(new TwoWaySerialComm()).connect("COM5");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}


[실행 결과]

serial_1.PNG


KeyBorad Input Read!!!가 출력되면 그 뒤로 키보드 입력을 하면 반대편 즉 COM5에 연결된 시리얼 쪽으로

데이터를 보내게 됩니다. 반대로 반대편에서 키보드 입력을 하면 받은 데이터를 문자열로 출력 하게 됩니다.

문자열로 출력을 하다보면 글자가 깨지는 현상이 있으니 일단은 숫자로만 체크를 해보세요.



감사합니다.