import javax.comm.*; import java.io.*; public class SerialPortHandler { protected SerialPort port; public SerialPortHandler(String portName){ CommPortIdentifier portID = null; try{ // CommPortIdentifier を取得 portID = CommPortIdentifier.getPortIdentifier(portName); }catch(NoSuchPortException ex){ ex.printStackTrace(); System.exit(1); } try{ // ポートのオープン port = (SerialPort)portID.open("SerialPortWriter", 5000); }catch(PortInUseException ex){ // タイムアウトを過ぎた場合 ex.printStackTrace(); System.exit(1); } try { // 通信条件の設定 port.setSerialPortParams(9600, // 通信速度 9600 baud SerialPort.DATABITS_8, // データビット 8bit SerialPort.STOPBITS_1, // ストップビット 1bit SerialPort.PARITY_NONE); // パリティ なし // フローコントロールの設定 // ここではハードフローコントロール(RTS/CTS) を使用 port.setFlowControlMode(SerialPort.FLOWCONTROL_RTSCTS_IN | SerialPort.FLOWCONTROL_RTSCTS_OUT); } catch (UnsupportedCommOperationException ex){ ex.printStackTrace(); System.exit(1); } } public void close(){ port.close(); } }